sieve-manage: use auth-source.
[emacs.git] / src / process.c
blob370fb673e840c936793b3ddc325a3db9b3627475
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
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #include <fcntl.h>
40 /* Only MS-DOS does not define `subprocesses'. */
41 #ifdef subprocesses
43 #include <sys/socket.h>
44 #include <netdb.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
48 /* Are local (unix) sockets supported? */
49 #if defined (HAVE_SYS_UN_H)
50 #if !defined (AF_LOCAL) && defined (AF_UNIX)
51 #define AF_LOCAL AF_UNIX
52 #endif
53 #ifdef AF_LOCAL
54 #define HAVE_LOCAL_SOCKETS
55 #include <sys/un.h>
56 #endif
57 #endif
59 #if defined(HAVE_SYS_IOCTL_H)
60 #include <sys/ioctl.h>
61 #if defined(HAVE_NET_IF_H)
62 #include <net/if.h>
63 #endif /* HAVE_NET_IF_H */
64 #endif /* HAVE_SYS_IOCTL_H */
66 #ifdef NEED_BSDTTY
67 #include <bsdtty.h>
68 #endif
70 #ifdef HAVE_RES_INIT
71 #include <netinet/in.h>
72 #include <arpa/nameser.h>
73 #include <resolv.h>
74 #endif
76 #ifdef HAVE_UTIL_H
77 #include <util.h>
78 #endif
80 #ifdef HAVE_PTY_H
81 #include <pty.h>
82 #endif
84 #endif /* subprocesses */
86 #include "lisp.h"
87 #include "systime.h"
88 #include "systty.h"
90 #include "window.h"
91 #include "buffer.h"
92 #include "character.h"
93 #include "coding.h"
94 #include "process.h"
95 #include "frame.h"
96 #include "termhooks.h"
97 #include "termopts.h"
98 #include "commands.h"
99 #include "keyboard.h"
100 #include "blockinput.h"
101 #include "dispextern.h"
102 #include "composite.h"
103 #include "atimer.h"
104 #include "sysselect.h"
105 #include "syssignal.h"
106 #include "syswait.h"
107 #ifdef HAVE_GNUTLS
108 #include "gnutls.h"
109 #endif
111 #if defined (USE_GTK) || defined (HAVE_GCONF)
112 #include "xgselect.h"
113 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
114 #ifdef HAVE_NS
115 #include "nsterm.h"
116 #endif
118 extern int timers_run;
120 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
121 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
122 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
123 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
124 Lisp_Object QCname, QCtype;
126 /* Non-zero if keyboard input is on hold, zero otherwise. */
128 static int kbd_is_on_hold;
130 /* Nonzero means delete a process right away if it exits. */
131 static int delete_exited_processes;
133 /* Nonzero means don't run process sentinels. This is used
134 when exiting. */
135 int inhibit_sentinels;
137 #ifdef subprocesses
139 Lisp_Object Qprocessp;
140 Lisp_Object Qrun, Qstop, Qsignal;
141 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
142 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
143 Lisp_Object Qreal, Qnetwork, Qserial;
144 #ifdef AF_INET6
145 Lisp_Object Qipv6;
146 #endif
147 Lisp_Object QCport, QCspeed, QCprocess;
148 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
149 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
150 Lisp_Object QCbuffer, QChost, QCservice;
151 Lisp_Object QClocal, QCremote, QCcoding;
152 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
153 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
154 Lisp_Object Qlast_nonmenu_event;
155 /* QCfamily is declared and initialized in xfaces.c,
156 QCfilter in keyboard.c. */
157 extern Lisp_Object QCfamily, QCfilter;
159 /* Qexit is declared and initialized in eval.c. */
161 /* QCfamily is defined in xfaces.c. */
162 extern Lisp_Object QCfamily;
163 /* QCfilter is defined in keyboard.c. */
164 extern Lisp_Object QCfilter;
166 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
167 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
168 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
169 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
171 /* Define first descriptor number available for subprocesses. */
172 #define FIRST_PROC_DESC 3
174 extern const char *get_operating_system_release (void);
176 /* From sysdep.c or w32.c */
177 extern int serial_open (char *port);
178 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
180 #ifndef HAVE_H_ERRNO
181 extern int h_errno;
182 #endif
184 /* t means use pty, nil means use a pipe,
185 maybe other values to come. */
186 static Lisp_Object Vprocess_connection_type;
188 /* These next two vars are non-static since sysdep.c uses them in the
189 emulation of `select'. */
190 /* Number of events of change of status of a process. */
191 int process_tick;
192 /* Number of events for which the user or sentinel has been notified. */
193 int update_tick;
195 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
197 /* Only W32 has this, it really means that select can't take write mask. */
198 #ifdef BROKEN_NON_BLOCKING_CONNECT
199 #undef NON_BLOCKING_CONNECT
200 #define SELECT_CANT_DO_WRITE_MASK
201 #else
202 #ifndef NON_BLOCKING_CONNECT
203 #ifdef HAVE_SELECT
204 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
205 #if defined (O_NONBLOCK) || defined (O_NDELAY)
206 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
207 #define NON_BLOCKING_CONNECT
208 #endif /* EWOULDBLOCK || EINPROGRESS */
209 #endif /* O_NONBLOCK || O_NDELAY */
210 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
211 #endif /* HAVE_SELECT */
212 #endif /* NON_BLOCKING_CONNECT */
213 #endif /* BROKEN_NON_BLOCKING_CONNECT */
215 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
216 this system. We need to read full packets, so we need a
217 "non-destructive" select. So we require either native select,
218 or emulation of select using FIONREAD. */
220 #ifdef BROKEN_DATAGRAM_SOCKETS
221 #undef DATAGRAM_SOCKETS
222 #else
223 #ifndef DATAGRAM_SOCKETS
224 #if defined (HAVE_SELECT) || defined (FIONREAD)
225 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
226 #define DATAGRAM_SOCKETS
227 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
228 #endif /* HAVE_SELECT || FIONREAD */
229 #endif /* DATAGRAM_SOCKETS */
230 #endif /* BROKEN_DATAGRAM_SOCKETS */
232 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
233 # define HAVE_SEQPACKET
234 #endif
236 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
237 #ifdef EMACS_HAS_USECS
238 #define ADAPTIVE_READ_BUFFERING
239 #endif
240 #endif
242 #ifdef ADAPTIVE_READ_BUFFERING
243 #define READ_OUTPUT_DELAY_INCREMENT 10000
244 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
245 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
247 /* Number of processes which have a non-zero read_output_delay,
248 and therefore might be delayed for adaptive read buffering. */
250 static int process_output_delay_count;
252 /* Non-zero if any process has non-nil read_output_skip. */
254 static int process_output_skip;
256 /* Non-nil means to delay reading process output to improve buffering.
257 A value of t means that delay is reset after each send, any other
258 non-nil value does not reset the delay. A value of nil disables
259 adaptive read buffering completely. */
260 static Lisp_Object Vprocess_adaptive_read_buffering;
261 #else
262 #define process_output_delay_count 0
263 #endif
265 static int keyboard_bit_set (SELECT_TYPE *);
266 static void deactivate_process (Lisp_Object);
267 static void status_notify (struct Lisp_Process *);
268 static int read_process_output (Lisp_Object, int);
269 static void create_pty (Lisp_Object);
271 /* If we support a window system, turn on the code to poll periodically
272 to detect C-g. It isn't actually used when doing interrupt input. */
273 #ifdef HAVE_WINDOW_SYSTEM
274 #define POLL_FOR_INPUT
275 #endif
277 static Lisp_Object get_process (register Lisp_Object name);
278 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
280 /* Mask of bits indicating the descriptors that we wait for input on. */
282 static SELECT_TYPE input_wait_mask;
284 /* Mask that excludes keyboard input descriptor(s). */
286 static SELECT_TYPE non_keyboard_wait_mask;
288 /* Mask that excludes process input descriptor(s). */
290 static SELECT_TYPE non_process_wait_mask;
292 /* Mask for selecting for write. */
294 static SELECT_TYPE write_mask;
296 #ifdef NON_BLOCKING_CONNECT
297 /* Mask of bits indicating the descriptors that we wait for connect to
298 complete on. Once they complete, they are removed from this mask
299 and added to the input_wait_mask and non_keyboard_wait_mask. */
301 static SELECT_TYPE connect_wait_mask;
303 /* Number of bits set in connect_wait_mask. */
304 static int num_pending_connects;
306 #define IF_NON_BLOCKING_CONNECT(s) s
307 #else /* NON_BLOCKING_CONNECT */
308 #define IF_NON_BLOCKING_CONNECT(s)
309 #endif /* NON_BLOCKING_CONNECT */
311 /* The largest descriptor currently in use for a process object. */
312 static int max_process_desc;
314 /* The largest descriptor currently in use for input. */
315 static int max_input_desc;
317 /* Indexed by descriptor, gives the process (if any) for that descriptor */
318 Lisp_Object chan_process[MAXDESC];
320 /* Alist of elements (NAME . PROCESS) */
321 Lisp_Object Vprocess_alist;
323 /* Buffered-ahead input char from process, indexed by channel.
324 -1 means empty (no char is buffered).
325 Used on sys V where the only way to tell if there is any
326 output from the process is to read at least one char.
327 Always -1 on systems that support FIONREAD. */
329 /* Don't make static; need to access externally. */
330 int proc_buffered_char[MAXDESC];
332 /* Table of `struct coding-system' for each process. */
333 static struct coding_system *proc_decode_coding_system[MAXDESC];
334 static struct coding_system *proc_encode_coding_system[MAXDESC];
336 #ifdef DATAGRAM_SOCKETS
337 /* Table of `partner address' for datagram sockets. */
338 struct sockaddr_and_len {
339 struct sockaddr *sa;
340 int len;
341 } datagram_address[MAXDESC];
342 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
343 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
344 #else
345 #define DATAGRAM_CHAN_P(chan) (0)
346 #define DATAGRAM_CONN_P(proc) (0)
347 #endif
349 /* Maximum number of bytes to send to a pty without an eof. */
350 static int pty_max_bytes;
354 struct fd_callback_data
356 fd_callback func;
357 void *data;
358 #define FOR_READ 1
359 #define FOR_WRITE 2
360 int condition; /* mask of the defines above. */
361 } fd_callback_info[MAXDESC];
364 /* Add a file descriptor FD to be monitored for when read is possible.
365 When read is possible, call FUNC with argument DATA. */
367 void
368 add_read_fd (int fd, fd_callback func, void *data)
370 xassert (fd < MAXDESC);
371 add_keyboard_wait_descriptor (fd);
373 fd_callback_info[fd].func = func;
374 fd_callback_info[fd].data = data;
375 fd_callback_info[fd].condition |= FOR_READ;
378 /* Stop monitoring file descriptor FD for when read is possible. */
380 void
381 delete_read_fd (int fd)
383 xassert (fd < MAXDESC);
384 delete_keyboard_wait_descriptor (fd);
386 fd_callback_info[fd].condition &= ~FOR_READ;
387 if (fd_callback_info[fd].condition == 0)
389 fd_callback_info[fd].func = 0;
390 fd_callback_info[fd].data = 0;
394 /* Add a file descriptor FD to be monitored for when write is possible.
395 When write is possible, call FUNC with argument DATA. */
397 void
398 add_write_fd (int fd, fd_callback func, void *data)
400 xassert (fd < MAXDESC);
401 FD_SET (fd, &write_mask);
402 if (fd > max_input_desc)
403 max_input_desc = fd;
405 fd_callback_info[fd].func = func;
406 fd_callback_info[fd].data = data;
407 fd_callback_info[fd].condition |= FOR_WRITE;
410 /* Stop monitoring file descriptor FD for when write is possible. */
412 void
413 delete_write_fd (int fd)
415 int lim = max_input_desc;
417 xassert (fd < MAXDESC);
418 FD_CLR (fd, &write_mask);
419 fd_callback_info[fd].condition &= ~FOR_WRITE;
420 if (fd_callback_info[fd].condition == 0)
422 fd_callback_info[fd].func = 0;
423 fd_callback_info[fd].data = 0;
425 if (fd == max_input_desc)
426 for (fd = lim; fd >= 0; fd--)
427 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
429 max_input_desc = fd;
430 break;
437 /* Compute the Lisp form of the process status, p->status, from
438 the numeric status that was returned by `wait'. */
440 static Lisp_Object status_convert (int);
442 static void
443 update_status (struct Lisp_Process *p)
445 eassert (p->raw_status_new);
446 p->status = status_convert (p->raw_status);
447 p->raw_status_new = 0;
450 /* Convert a process status word in Unix format to
451 the list that we use internally. */
453 static Lisp_Object
454 status_convert (int w)
456 if (WIFSTOPPED (w))
457 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
458 else if (WIFEXITED (w))
459 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
460 WCOREDUMP (w) ? Qt : Qnil));
461 else if (WIFSIGNALED (w))
462 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
463 WCOREDUMP (w) ? Qt : Qnil));
464 else
465 return Qrun;
468 /* Given a status-list, extract the three pieces of information
469 and store them individually through the three pointers. */
471 static void
472 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
474 Lisp_Object tem;
476 if (SYMBOLP (l))
478 *symbol = l;
479 *code = 0;
480 *coredump = 0;
482 else
484 *symbol = XCAR (l);
485 tem = XCDR (l);
486 *code = XFASTINT (XCAR (tem));
487 tem = XCDR (tem);
488 *coredump = !NILP (tem);
492 /* Return a string describing a process status list. */
494 static Lisp_Object
495 status_message (struct Lisp_Process *p)
497 Lisp_Object status = p->status;
498 Lisp_Object symbol;
499 int code, coredump;
500 Lisp_Object string, string2;
502 decode_status (status, &symbol, &code, &coredump);
504 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
506 char *signame;
507 synchronize_system_messages_locale ();
508 signame = strsignal (code);
509 if (signame == 0)
510 string = build_string ("unknown");
511 else
513 int c1, c2;
515 string = make_unibyte_string (signame, strlen (signame));
516 if (! NILP (Vlocale_coding_system))
517 string = (code_convert_string_norecord
518 (string, Vlocale_coding_system, 0));
519 c1 = STRING_CHAR ((char *) SDATA (string));
520 c2 = DOWNCASE (c1);
521 if (c1 != c2)
522 Faset (string, make_number (0), make_number (c2));
524 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
525 return concat2 (string, string2);
527 else if (EQ (symbol, Qexit))
529 if (NETCONN1_P (p))
530 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
531 if (code == 0)
532 return build_string ("finished\n");
533 string = Fnumber_to_string (make_number (code));
534 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
535 return concat3 (build_string ("exited abnormally with code "),
536 string, string2);
538 else if (EQ (symbol, Qfailed))
540 string = Fnumber_to_string (make_number (code));
541 string2 = build_string ("\n");
542 return concat3 (build_string ("failed with code "),
543 string, string2);
545 else
546 return Fcopy_sequence (Fsymbol_name (symbol));
549 #ifdef HAVE_PTYS
551 /* The file name of the pty opened by allocate_pty. */
552 static char pty_name[24];
554 /* Open an available pty, returning a file descriptor.
555 Return -1 on failure.
556 The file name of the terminal corresponding to the pty
557 is left in the variable pty_name. */
559 static int
560 allocate_pty (void)
562 register int c, i;
563 int fd;
565 #ifdef PTY_ITERATION
566 PTY_ITERATION
567 #else
568 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
569 for (i = 0; i < 16; i++)
570 #endif
572 struct stat stb; /* Used in some PTY_OPEN. */
573 #ifdef PTY_NAME_SPRINTF
574 PTY_NAME_SPRINTF
575 #else
576 sprintf (pty_name, "/dev/pty%c%x", c, i);
577 #endif /* no PTY_NAME_SPRINTF */
579 #ifdef PTY_OPEN
580 PTY_OPEN;
581 #else /* no PTY_OPEN */
583 { /* Some systems name their pseudoterminals so that there are gaps in
584 the usual sequence - for example, on HP9000/S700 systems, there
585 are no pseudoterminals with names ending in 'f'. So we wait for
586 three failures in a row before deciding that we've reached the
587 end of the ptys. */
588 int failed_count = 0;
590 if (stat (pty_name, &stb) < 0)
592 failed_count++;
593 if (failed_count >= 3)
594 return -1;
596 else
597 failed_count = 0;
599 # ifdef O_NONBLOCK
600 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
601 # else
602 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
603 # endif
605 #endif /* no PTY_OPEN */
607 if (fd >= 0)
609 /* check to make certain that both sides are available
610 this avoids a nasty yet stupid bug in rlogins */
611 #ifdef PTY_TTY_NAME_SPRINTF
612 PTY_TTY_NAME_SPRINTF
613 #else
614 sprintf (pty_name, "/dev/tty%c%x", c, i);
615 #endif /* no PTY_TTY_NAME_SPRINTF */
616 if (access (pty_name, 6) != 0)
618 emacs_close (fd);
619 # ifndef __sgi
620 continue;
621 # else
622 return -1;
623 # endif /* __sgi */
625 setup_pty (fd);
626 return fd;
629 return -1;
631 #endif /* HAVE_PTYS */
633 static Lisp_Object
634 make_process (Lisp_Object name)
636 register Lisp_Object val, tem, name1;
637 register struct Lisp_Process *p;
638 char suffix[10];
639 register int i;
641 p = allocate_process ();
643 p->infd = -1;
644 p->outfd = -1;
645 p->tick = 0;
646 p->update_tick = 0;
647 p->pid = 0;
648 p->pty_flag = 0;
649 p->raw_status_new = 0;
650 p->status = Qrun;
651 p->mark = Fmake_marker ();
652 p->kill_without_query = 0;
654 #ifdef ADAPTIVE_READ_BUFFERING
655 p->adaptive_read_buffering = 0;
656 p->read_output_delay = 0;
657 p->read_output_skip = 0;
658 #endif
660 #ifdef HAVE_GNUTLS
661 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
662 p->gnutls_log_level = 0;
663 p->gnutls_p = 0;
664 #endif
666 /* If name is already in use, modify it until it is unused. */
668 name1 = name;
669 for (i = 1; ; i++)
671 tem = Fget_process (name1);
672 if (NILP (tem)) break;
673 sprintf (suffix, "<%d>", i);
674 name1 = concat2 (name, build_string (suffix));
676 name = name1;
677 p->name = name;
678 XSETPROCESS (val, p);
679 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
680 return val;
683 static void
684 remove_process (register Lisp_Object proc)
686 register Lisp_Object pair;
688 pair = Frassq (proc, Vprocess_alist);
689 Vprocess_alist = Fdelq (pair, Vprocess_alist);
691 deactivate_process (proc);
695 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
696 doc: /* Return t if OBJECT is a process. */)
697 (Lisp_Object object)
699 return PROCESSP (object) ? Qt : Qnil;
702 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
703 doc: /* Return the process named NAME, or nil if there is none. */)
704 (register Lisp_Object name)
706 if (PROCESSP (name))
707 return name;
708 CHECK_STRING (name);
709 return Fcdr (Fassoc (name, Vprocess_alist));
712 /* This is how commands for the user decode process arguments. It
713 accepts a process, a process name, a buffer, a buffer name, or nil.
714 Buffers denote the first process in the buffer, and nil denotes the
715 current buffer. */
717 static Lisp_Object
718 get_process (register Lisp_Object name)
720 register Lisp_Object proc, obj;
721 if (STRINGP (name))
723 obj = Fget_process (name);
724 if (NILP (obj))
725 obj = Fget_buffer (name);
726 if (NILP (obj))
727 error ("Process %s does not exist", SDATA (name));
729 else if (NILP (name))
730 obj = Fcurrent_buffer ();
731 else
732 obj = name;
734 /* Now obj should be either a buffer object or a process object.
736 if (BUFFERP (obj))
738 proc = Fget_buffer_process (obj);
739 if (NILP (proc))
740 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
742 else
744 CHECK_PROCESS (obj);
745 proc = obj;
747 return proc;
751 #ifdef SIGCHLD
752 /* Fdelete_process promises to immediately forget about the process, but in
753 reality, Emacs needs to remember those processes until they have been
754 treated by sigchld_handler; otherwise this handler would consider the
755 process as being synchronous and say that the synchronous process is
756 dead. */
757 static Lisp_Object deleted_pid_list;
758 #endif
760 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
761 doc: /* Delete PROCESS: kill it and forget about it immediately.
762 PROCESS may be a process, a buffer, the name of a process or buffer, or
763 nil, indicating the current buffer's process. */)
764 (register Lisp_Object process)
766 register struct Lisp_Process *p;
768 process = get_process (process);
769 p = XPROCESS (process);
771 p->raw_status_new = 0;
772 if (NETCONN1_P (p) || SERIALCONN1_P (p))
774 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
775 p->tick = ++process_tick;
776 status_notify (p);
777 redisplay_preserve_echo_area (13);
779 else if (p->infd >= 0)
781 #ifdef SIGCHLD
782 Lisp_Object symbol;
783 /* Assignment to EMACS_INT stops GCC whining about limited range
784 of data type. */
785 EMACS_INT pid = p->pid;
787 /* No problem storing the pid here, as it is still in Vprocess_alist. */
788 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
789 /* GC treated elements set to nil. */
790 Fdelq (Qnil, deleted_pid_list));
791 /* If the process has already signaled, remove it from the list. */
792 if (p->raw_status_new)
793 update_status (p);
794 symbol = p->status;
795 if (CONSP (p->status))
796 symbol = XCAR (p->status);
797 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
798 deleted_pid_list
799 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
800 else
801 #endif
803 Fkill_process (process, Qnil);
804 /* Do this now, since remove_process will make sigchld_handler do nothing. */
805 p->status
806 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
807 p->tick = ++process_tick;
808 status_notify (p);
809 redisplay_preserve_echo_area (13);
812 remove_process (process);
813 return Qnil;
816 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
817 doc: /* Return the status of PROCESS.
818 The returned value is one of the following symbols:
819 run -- for a process that is running.
820 stop -- for a process stopped but continuable.
821 exit -- for a process that has exited.
822 signal -- for a process that has got a fatal signal.
823 open -- for a network stream connection that is open.
824 listen -- for a network stream server that is listening.
825 closed -- for a network stream connection that is closed.
826 connect -- when waiting for a non-blocking connection to complete.
827 failed -- when a non-blocking connection has failed.
828 nil -- if arg is a process name and no such process exists.
829 PROCESS may be a process, a buffer, the name of a process, or
830 nil, indicating the current buffer's process. */)
831 (register Lisp_Object process)
833 register struct Lisp_Process *p;
834 register Lisp_Object status;
836 if (STRINGP (process))
837 process = Fget_process (process);
838 else
839 process = get_process (process);
841 if (NILP (process))
842 return process;
844 p = XPROCESS (process);
845 if (p->raw_status_new)
846 update_status (p);
847 status = p->status;
848 if (CONSP (status))
849 status = XCAR (status);
850 if (NETCONN1_P (p) || SERIALCONN1_P (p))
852 if (EQ (status, Qexit))
853 status = Qclosed;
854 else if (EQ (p->command, Qt))
855 status = Qstop;
856 else if (EQ (status, Qrun))
857 status = Qopen;
859 return status;
862 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
863 1, 1, 0,
864 doc: /* Return the exit status of PROCESS or the signal number that killed it.
865 If PROCESS has not yet exited or died, return 0. */)
866 (register Lisp_Object process)
868 CHECK_PROCESS (process);
869 if (XPROCESS (process)->raw_status_new)
870 update_status (XPROCESS (process));
871 if (CONSP (XPROCESS (process)->status))
872 return XCAR (XCDR (XPROCESS (process)->status));
873 return make_number (0);
876 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
877 doc: /* Return the process id of PROCESS.
878 This is the pid of the external process which PROCESS uses or talks to.
879 For a network connection, this value is nil. */)
880 (register Lisp_Object process)
882 /* Assignment to EMACS_INT stops GCC whining about limited range of
883 data type. */
884 EMACS_INT pid;
886 CHECK_PROCESS (process);
887 pid = XPROCESS (process)->pid;
888 return (pid ? make_fixnum_or_float (pid) : Qnil);
891 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
892 doc: /* Return the name of PROCESS, as a string.
893 This is the name of the program invoked in PROCESS,
894 possibly modified to make it unique among process names. */)
895 (register Lisp_Object process)
897 CHECK_PROCESS (process);
898 return XPROCESS (process)->name;
901 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
902 doc: /* Return the command that was executed to start PROCESS.
903 This is a list of strings, the first string being the program executed
904 and the rest of the strings being the arguments given to it.
905 For a network or serial process, this is nil (process is running) or t
906 \(process is stopped). */)
907 (register Lisp_Object process)
909 CHECK_PROCESS (process);
910 return XPROCESS (process)->command;
913 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
914 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
915 This is the terminal that the process itself reads and writes on,
916 not the name of the pty that Emacs uses to talk with that terminal. */)
917 (register Lisp_Object process)
919 CHECK_PROCESS (process);
920 return XPROCESS (process)->tty_name;
923 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
924 2, 2, 0,
925 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
926 (register Lisp_Object process, Lisp_Object buffer)
928 struct Lisp_Process *p;
930 CHECK_PROCESS (process);
931 if (!NILP (buffer))
932 CHECK_BUFFER (buffer);
933 p = XPROCESS (process);
934 p->buffer = buffer;
935 if (NETCONN1_P (p) || SERIALCONN1_P (p))
936 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
937 setup_process_coding_systems (process);
938 return buffer;
941 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
942 1, 1, 0,
943 doc: /* Return the buffer PROCESS is associated with.
944 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
945 (register Lisp_Object process)
947 CHECK_PROCESS (process);
948 return XPROCESS (process)->buffer;
951 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
952 1, 1, 0,
953 doc: /* Return the marker for the end of the last output from PROCESS. */)
954 (register Lisp_Object process)
956 CHECK_PROCESS (process);
957 return XPROCESS (process)->mark;
960 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
961 2, 2, 0,
962 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
963 A value of t means stop accepting output from the process.
965 When a process has a filter, its buffer is not used for output.
966 Instead, each time it does output, the entire string of output is
967 passed to the filter.
969 The filter gets two arguments: the process and the string of output.
970 The string argument is normally a multibyte string, except:
971 - if the process' input coding system is no-conversion or raw-text,
972 it is a unibyte string (the non-converted input), or else
973 - if `default-enable-multibyte-characters' is nil, it is a unibyte
974 string (the result of converting the decoded input multibyte
975 string to unibyte with `string-make-unibyte'). */)
976 (register Lisp_Object process, Lisp_Object filter)
978 struct Lisp_Process *p;
980 CHECK_PROCESS (process);
981 p = XPROCESS (process);
983 /* Don't signal an error if the process' input file descriptor
984 is closed. This could make debugging Lisp more difficult,
985 for example when doing something like
987 (setq process (start-process ...))
988 (debug)
989 (set-process-filter process ...) */
991 if (p->infd >= 0)
993 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
995 FD_CLR (p->infd, &input_wait_mask);
996 FD_CLR (p->infd, &non_keyboard_wait_mask);
998 else if (EQ (p->filter, Qt)
999 /* Network or serial process not stopped: */
1000 && !EQ (p->command, Qt))
1002 FD_SET (p->infd, &input_wait_mask);
1003 FD_SET (p->infd, &non_keyboard_wait_mask);
1007 p->filter = filter;
1008 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1009 p->childp = Fplist_put (p->childp, QCfilter, filter);
1010 setup_process_coding_systems (process);
1011 return filter;
1014 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1015 1, 1, 0,
1016 doc: /* Returns the filter function of PROCESS; nil if none.
1017 See `set-process-filter' for more info on filter functions. */)
1018 (register Lisp_Object process)
1020 CHECK_PROCESS (process);
1021 return XPROCESS (process)->filter;
1024 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1025 2, 2, 0,
1026 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1027 The sentinel is called as a function when the process changes state.
1028 It gets two arguments: the process, and a string describing the change. */)
1029 (register Lisp_Object process, Lisp_Object sentinel)
1031 struct Lisp_Process *p;
1033 CHECK_PROCESS (process);
1034 p = XPROCESS (process);
1036 p->sentinel = sentinel;
1037 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1038 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1039 return sentinel;
1042 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1043 1, 1, 0,
1044 doc: /* Return the sentinel of PROCESS; nil if none.
1045 See `set-process-sentinel' for more info on sentinels. */)
1046 (register Lisp_Object process)
1048 CHECK_PROCESS (process);
1049 return XPROCESS (process)->sentinel;
1052 DEFUN ("set-process-window-size", Fset_process_window_size,
1053 Sset_process_window_size, 3, 3, 0,
1054 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1055 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1057 CHECK_PROCESS (process);
1058 CHECK_NATNUM (height);
1059 CHECK_NATNUM (width);
1061 if (XPROCESS (process)->infd < 0
1062 || set_window_size (XPROCESS (process)->infd,
1063 XINT (height), XINT (width)) <= 0)
1064 return Qnil;
1065 else
1066 return Qt;
1069 DEFUN ("set-process-inherit-coding-system-flag",
1070 Fset_process_inherit_coding_system_flag,
1071 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1072 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1073 If the second argument FLAG is non-nil, then the variable
1074 `buffer-file-coding-system' of the buffer associated with PROCESS
1075 will be bound to the value of the coding system used to decode
1076 the process output.
1078 This is useful when the coding system specified for the process buffer
1079 leaves either the character code conversion or the end-of-line conversion
1080 unspecified, or if the coding system used to decode the process output
1081 is more appropriate for saving the process buffer.
1083 Binding the variable `inherit-process-coding-system' to non-nil before
1084 starting the process is an alternative way of setting the inherit flag
1085 for the process which will run. */)
1086 (register Lisp_Object process, Lisp_Object flag)
1088 CHECK_PROCESS (process);
1089 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1090 return flag;
1093 DEFUN ("set-process-query-on-exit-flag",
1094 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1095 2, 2, 0,
1096 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1097 If the second argument FLAG is non-nil, Emacs will query the user before
1098 exiting or killing a buffer if PROCESS is running. */)
1099 (register Lisp_Object process, Lisp_Object flag)
1101 CHECK_PROCESS (process);
1102 XPROCESS (process)->kill_without_query = NILP (flag);
1103 return flag;
1106 DEFUN ("process-query-on-exit-flag",
1107 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1108 1, 1, 0,
1109 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1110 (register Lisp_Object process)
1112 CHECK_PROCESS (process);
1113 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1116 #ifdef DATAGRAM_SOCKETS
1117 Lisp_Object Fprocess_datagram_address (Lisp_Object process);
1118 #endif
1120 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1121 1, 2, 0,
1122 doc: /* Return the contact info of PROCESS; t for a real child.
1123 For a network or serial connection, the value depends on the optional
1124 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1125 SERVICE) for a network connection or (PORT SPEED) for a serial
1126 connection. If KEY is t, the complete contact information for the
1127 connection is returned, else the specific value for the keyword KEY is
1128 returned. See `make-network-process' or `make-serial-process' for a
1129 list of keywords. */)
1130 (register Lisp_Object process, Lisp_Object key)
1132 Lisp_Object contact;
1134 CHECK_PROCESS (process);
1135 contact = XPROCESS (process)->childp;
1137 #ifdef DATAGRAM_SOCKETS
1138 if (DATAGRAM_CONN_P (process)
1139 && (EQ (key, Qt) || EQ (key, QCremote)))
1140 contact = Fplist_put (contact, QCremote,
1141 Fprocess_datagram_address (process));
1142 #endif
1144 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1145 return contact;
1146 if (NILP (key) && NETCONN_P (process))
1147 return Fcons (Fplist_get (contact, QChost),
1148 Fcons (Fplist_get (contact, QCservice), Qnil));
1149 if (NILP (key) && SERIALCONN_P (process))
1150 return Fcons (Fplist_get (contact, QCport),
1151 Fcons (Fplist_get (contact, QCspeed), Qnil));
1152 return Fplist_get (contact, key);
1155 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1156 1, 1, 0,
1157 doc: /* Return the plist of PROCESS. */)
1158 (register Lisp_Object process)
1160 CHECK_PROCESS (process);
1161 return XPROCESS (process)->plist;
1164 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1165 2, 2, 0,
1166 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1167 (register Lisp_Object process, Lisp_Object plist)
1169 CHECK_PROCESS (process);
1170 CHECK_LIST (plist);
1172 XPROCESS (process)->plist = plist;
1173 return plist;
1176 #if 0 /* Turned off because we don't currently record this info
1177 in the process. Perhaps add it. */
1178 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1179 doc: /* Return the connection type of PROCESS.
1180 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1181 a socket connection. */)
1182 (Lisp_Object process)
1184 return XPROCESS (process)->type;
1186 #endif
1188 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1189 doc: /* Return the connection type of PROCESS.
1190 The value is either the symbol `real', `network', or `serial'.
1191 PROCESS may be a process, a buffer, the name of a process or buffer, or
1192 nil, indicating the current buffer's process. */)
1193 (Lisp_Object process)
1195 Lisp_Object proc;
1196 proc = get_process (process);
1197 return XPROCESS (proc)->type;
1200 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1201 1, 2, 0,
1202 doc: /* Convert network ADDRESS from internal format to a string.
1203 A 4 or 5 element vector represents an IPv4 address (with port number).
1204 An 8 or 9 element vector represents an IPv6 address (with port number).
1205 If optional second argument OMIT-PORT is non-nil, don't include a port
1206 number in the string, even when present in ADDRESS.
1207 Returns nil if format of ADDRESS is invalid. */)
1208 (Lisp_Object address, Lisp_Object omit_port)
1210 if (NILP (address))
1211 return Qnil;
1213 if (STRINGP (address)) /* AF_LOCAL */
1214 return address;
1216 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1218 register struct Lisp_Vector *p = XVECTOR (address);
1219 Lisp_Object args[10];
1220 int nargs, i;
1222 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1224 args[0] = build_string ("%d.%d.%d.%d");
1225 nargs = 4;
1227 else if (p->size == 5)
1229 args[0] = build_string ("%d.%d.%d.%d:%d");
1230 nargs = 5;
1232 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1234 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1235 nargs = 8;
1237 else if (p->size == 9)
1239 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1240 nargs = 9;
1242 else
1243 return Qnil;
1245 for (i = 0; i < nargs; i++)
1247 EMACS_INT element = XINT (p->contents[i]);
1249 if (element < 0 || element > 65535)
1250 return Qnil;
1252 if (nargs <= 5 /* IPv4 */
1253 && i < 4 /* host, not port */
1254 && element > 255)
1255 return Qnil;
1257 args[i+1] = p->contents[i];
1260 return Fformat (nargs+1, args);
1263 if (CONSP (address))
1265 Lisp_Object args[2];
1266 args[0] = build_string ("<Family %d>");
1267 args[1] = Fcar (address);
1268 return Fformat (2, args);
1271 return Qnil;
1274 static Lisp_Object
1275 list_processes_1 (Lisp_Object query_only)
1277 register Lisp_Object tail, tem;
1278 Lisp_Object proc, minspace, tem1;
1279 register struct Lisp_Process *p;
1280 char tembuf[300];
1281 int w_proc, w_buffer, w_tty;
1282 int exited = 0;
1283 Lisp_Object i_status, i_buffer, i_tty, i_command;
1285 w_proc = 4; /* Proc */
1286 w_buffer = 6; /* Buffer */
1287 w_tty = 0; /* Omit if no ttys */
1289 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1291 int i;
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;
1299 if (STRINGP (p->name)
1300 && ( i = SCHARS (p->name), (i > w_proc)))
1301 w_proc = i;
1302 if (!NILP (p->buffer))
1304 if (NILP (XBUFFER (p->buffer)->name))
1306 if (w_buffer < 8)
1307 w_buffer = 8; /* (Killed) */
1309 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1310 w_buffer = i;
1312 if (STRINGP (p->tty_name)
1313 && (i = SCHARS (p->tty_name), (i > w_tty)))
1314 w_tty = i;
1317 XSETFASTINT (i_status, w_proc + 1);
1318 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1319 if (w_tty)
1321 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1322 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1324 else
1326 i_tty = Qnil;
1327 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1330 XSETFASTINT (minspace, 1);
1332 set_buffer_internal (XBUFFER (Vstandard_output));
1333 current_buffer->undo_list = Qt;
1335 current_buffer->truncate_lines = Qt;
1337 write_string ("Proc", -1);
1338 Findent_to (i_status, minspace); write_string ("Status", -1);
1339 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1340 if (!NILP (i_tty))
1342 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1344 Findent_to (i_command, minspace); write_string ("Command", -1);
1345 write_string ("\n", -1);
1347 write_string ("----", -1);
1348 Findent_to (i_status, minspace); write_string ("------", -1);
1349 Findent_to (i_buffer, minspace); write_string ("------", -1);
1350 if (!NILP (i_tty))
1352 Findent_to (i_tty, minspace); write_string ("---", -1);
1354 Findent_to (i_command, minspace); write_string ("-------", -1);
1355 write_string ("\n", -1);
1357 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1359 Lisp_Object symbol;
1361 proc = Fcdr (XCAR (tail));
1362 p = XPROCESS (proc);
1363 if (NILP (p->type))
1364 continue;
1365 if (!NILP (query_only) && p->kill_without_query)
1366 continue;
1368 Finsert (1, &p->name);
1369 Findent_to (i_status, minspace);
1371 if (p->raw_status_new)
1372 update_status (p);
1373 symbol = p->status;
1374 if (CONSP (p->status))
1375 symbol = XCAR (p->status);
1377 if (EQ (symbol, Qsignal))
1379 Lisp_Object tem;
1380 tem = Fcar (Fcdr (p->status));
1381 Fprinc (symbol, Qnil);
1383 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1385 if (EQ (symbol, Qexit))
1386 write_string ("closed", -1);
1387 else if (EQ (p->command, Qt))
1388 write_string ("stopped", -1);
1389 else if (EQ (symbol, Qrun))
1390 write_string ("open", -1);
1391 else
1392 Fprinc (symbol, Qnil);
1394 else if (SERIALCONN1_P (p))
1396 write_string ("running", -1);
1398 else
1399 Fprinc (symbol, Qnil);
1401 if (EQ (symbol, Qexit))
1403 Lisp_Object tem;
1404 tem = Fcar (Fcdr (p->status));
1405 if (XFASTINT (tem))
1407 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1408 write_string (tembuf, -1);
1412 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1413 exited++;
1415 Findent_to (i_buffer, minspace);
1416 if (NILP (p->buffer))
1417 insert_string ("(none)");
1418 else if (NILP (XBUFFER (p->buffer)->name))
1419 insert_string ("(Killed)");
1420 else
1421 Finsert (1, &XBUFFER (p->buffer)->name);
1423 if (!NILP (i_tty))
1425 Findent_to (i_tty, minspace);
1426 if (STRINGP (p->tty_name))
1427 Finsert (1, &p->tty_name);
1430 Findent_to (i_command, minspace);
1432 if (EQ (p->status, Qlisten))
1434 Lisp_Object port = Fplist_get (p->childp, QCservice);
1435 if (INTEGERP (port))
1436 port = Fnumber_to_string (port);
1437 if (NILP (port))
1438 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1439 sprintf (tembuf, "(network %s server on %s)\n",
1440 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1441 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1442 insert_string (tembuf);
1444 else if (NETCONN1_P (p))
1446 /* For a local socket, there is no host name,
1447 so display service instead. */
1448 Lisp_Object host = Fplist_get (p->childp, QChost);
1449 if (!STRINGP (host))
1451 host = Fplist_get (p->childp, QCservice);
1452 if (INTEGERP (host))
1453 host = Fnumber_to_string (host);
1455 if (NILP (host))
1456 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1457 sprintf (tembuf, "(network %s connection to %s)\n",
1458 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1459 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1460 insert_string (tembuf);
1462 else if (SERIALCONN1_P (p))
1464 Lisp_Object port = Fplist_get (p->childp, QCport);
1465 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1466 insert_string ("(serial port ");
1467 if (STRINGP (port))
1468 insert_string (SDATA (port));
1469 else
1470 insert_string ("?");
1471 if (INTEGERP (speed))
1473 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1474 insert_string (tembuf);
1476 insert_string (")\n");
1478 else
1480 tem = p->command;
1481 while (1)
1483 tem1 = Fcar (tem);
1484 if (NILP (tem1))
1485 break;
1486 Finsert (1, &tem1);
1487 tem = Fcdr (tem);
1488 if (NILP (tem))
1489 break;
1490 insert_string (" ");
1492 insert_string ("\n");
1495 if (exited)
1497 status_notify (NULL);
1498 redisplay_preserve_echo_area (13);
1500 return Qnil;
1503 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1504 doc: /* Display a list of all processes.
1505 If optional argument QUERY-ONLY is non-nil, only processes with
1506 the query-on-exit flag set will be listed.
1507 Any process listed as exited or signaled is actually eliminated
1508 after the listing is made. */)
1509 (Lisp_Object query_only)
1511 internal_with_output_to_temp_buffer ("*Process List*",
1512 list_processes_1, query_only);
1513 return Qnil;
1516 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1517 doc: /* Return a list of all processes. */)
1518 (void)
1520 return Fmapcar (Qcdr, Vprocess_alist);
1523 /* Starting asynchronous inferior processes. */
1525 static Lisp_Object start_process_unwind (Lisp_Object proc);
1527 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1528 doc: /* Start a program in a subprocess. Return the process object for it.
1529 NAME is name for process. It is modified if necessary to make it unique.
1530 BUFFER is the buffer (or buffer name) to associate with the process.
1532 Process output (both standard output and standard error streams) goes
1533 at end of BUFFER, unless you specify an output stream or filter
1534 function to handle the output. BUFFER may also be nil, meaning that
1535 this process is not associated with any buffer.
1537 PROGRAM is the program file name. It is searched for in PATH. If
1538 nil, just associate a pty with the buffer. Remaining arguments are
1539 strings to give program as arguments.
1541 If you want to separate standard output from standard error, invoke
1542 the command through a shell and redirect one of them using the shell
1543 syntax.
1545 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1546 (int nargs, register Lisp_Object *args)
1548 Lisp_Object buffer, name, program, proc, current_dir, tem;
1549 register unsigned char **new_argv;
1550 register int i;
1551 int count = SPECPDL_INDEX ();
1553 buffer = args[1];
1554 if (!NILP (buffer))
1555 buffer = Fget_buffer_create (buffer);
1557 /* Make sure that the child will be able to chdir to the current
1558 buffer's current directory, or its unhandled equivalent. We
1559 can't just have the child check for an error when it does the
1560 chdir, since it's in a vfork.
1562 We have to GCPRO around this because Fexpand_file_name and
1563 Funhandled_file_name_directory might call a file name handling
1564 function. The argument list is protected by the caller, so all
1565 we really have to worry about is buffer. */
1567 struct gcpro gcpro1, gcpro2;
1569 current_dir = current_buffer->directory;
1571 GCPRO2 (buffer, current_dir);
1573 current_dir = Funhandled_file_name_directory (current_dir);
1574 if (NILP (current_dir))
1575 /* If the file name handler says that current_dir is unreachable, use
1576 a sensible default. */
1577 current_dir = build_string ("~/");
1578 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1579 if (NILP (Ffile_accessible_directory_p (current_dir)))
1580 report_file_error ("Setting current directory",
1581 Fcons (current_buffer->directory, Qnil));
1583 UNGCPRO;
1586 name = args[0];
1587 CHECK_STRING (name);
1589 program = args[2];
1591 if (!NILP (program))
1592 CHECK_STRING (program);
1594 proc = make_process (name);
1595 /* If an error occurs and we can't start the process, we want to
1596 remove it from the process list. This means that each error
1597 check in create_process doesn't need to call remove_process
1598 itself; it's all taken care of here. */
1599 record_unwind_protect (start_process_unwind, proc);
1601 XPROCESS (proc)->childp = Qt;
1602 XPROCESS (proc)->plist = Qnil;
1603 XPROCESS (proc)->type = Qreal;
1604 XPROCESS (proc)->buffer = buffer;
1605 XPROCESS (proc)->sentinel = Qnil;
1606 XPROCESS (proc)->filter = Qnil;
1607 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1609 #ifdef HAVE_GNUTLS
1610 /* AKA GNUTLS_INITSTAGE(proc). */
1611 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1612 XPROCESS (proc)->gnutls_cred_type = Qnil;
1613 #endif
1615 #ifdef ADAPTIVE_READ_BUFFERING
1616 XPROCESS (proc)->adaptive_read_buffering
1617 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1618 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1619 #endif
1621 /* Make the process marker point into the process buffer (if any). */
1622 if (BUFFERP (buffer))
1623 set_marker_both (XPROCESS (proc)->mark, buffer,
1624 BUF_ZV (XBUFFER (buffer)),
1625 BUF_ZV_BYTE (XBUFFER (buffer)));
1628 /* Decide coding systems for communicating with the process. Here
1629 we don't setup the structure coding_system nor pay attention to
1630 unibyte mode. They are done in create_process. */
1632 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1633 Lisp_Object coding_systems = Qt;
1634 Lisp_Object val, *args2;
1635 struct gcpro gcpro1, gcpro2;
1637 val = Vcoding_system_for_read;
1638 if (NILP (val))
1640 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1641 args2[0] = Qstart_process;
1642 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1643 GCPRO2 (proc, current_dir);
1644 if (!NILP (program))
1645 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1646 UNGCPRO;
1647 if (CONSP (coding_systems))
1648 val = XCAR (coding_systems);
1649 else if (CONSP (Vdefault_process_coding_system))
1650 val = XCAR (Vdefault_process_coding_system);
1652 XPROCESS (proc)->decode_coding_system = val;
1654 val = Vcoding_system_for_write;
1655 if (NILP (val))
1657 if (EQ (coding_systems, Qt))
1659 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1660 args2[0] = Qstart_process;
1661 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1662 GCPRO2 (proc, current_dir);
1663 if (!NILP (program))
1664 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1665 UNGCPRO;
1667 if (CONSP (coding_systems))
1668 val = XCDR (coding_systems);
1669 else if (CONSP (Vdefault_process_coding_system))
1670 val = XCDR (Vdefault_process_coding_system);
1672 XPROCESS (proc)->encode_coding_system = val;
1676 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1677 XPROCESS (proc)->decoding_carryover = 0;
1678 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1680 XPROCESS (proc)->inherit_coding_system_flag
1681 = !(NILP (buffer) || !inherit_process_coding_system);
1683 if (!NILP (program))
1685 /* If program file name is not absolute, search our path for it.
1686 Put the name we will really use in TEM. */
1687 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1688 && !(SCHARS (program) > 1
1689 && IS_DEVICE_SEP (SREF (program, 1))))
1691 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1693 tem = Qnil;
1694 GCPRO4 (name, program, buffer, current_dir);
1695 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1696 UNGCPRO;
1697 if (NILP (tem))
1698 report_file_error ("Searching for program", Fcons (program, Qnil));
1699 tem = Fexpand_file_name (tem, Qnil);
1701 else
1703 if (!NILP (Ffile_directory_p (program)))
1704 error ("Specified program for new process is a directory");
1705 tem = program;
1708 /* If program file name starts with /: for quoting a magic name,
1709 discard that. */
1710 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1711 && SREF (tem, 1) == ':')
1712 tem = Fsubstring (tem, make_number (2), Qnil);
1715 struct gcpro gcpro1;
1716 GCPRO1 (tem);
1718 /* Encode the file name and put it in NEW_ARGV.
1719 That's where the child will use it to execute the program. */
1720 tem = Fcons (ENCODE_FILE (tem), Qnil);
1722 /* Here we encode arguments by the coding system used for sending
1723 data to the process. We don't support using different coding
1724 systems for encoding arguments and for encoding data sent to the
1725 process. */
1727 for (i = 3; i < nargs; i++)
1729 tem = Fcons (args[i], tem);
1730 CHECK_STRING (XCAR (tem));
1731 if (STRING_MULTIBYTE (XCAR (tem)))
1732 XSETCAR (tem,
1733 code_convert_string_norecord
1734 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1737 UNGCPRO;
1740 /* Now that everything is encoded we can collect the strings into
1741 NEW_ARGV. */
1742 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1743 new_argv[nargs - 2] = 0;
1745 for (i = nargs - 3; i >= 0; i--)
1747 new_argv[i] = SDATA (XCAR (tem));
1748 tem = XCDR (tem);
1751 create_process (proc, (char **) new_argv, current_dir);
1753 else
1754 create_pty (proc);
1756 return unbind_to (count, proc);
1759 /* This function is the unwind_protect form for Fstart_process. If
1760 PROC doesn't have its pid set, then we know someone has signaled
1761 an error and the process wasn't started successfully, so we should
1762 remove it from the process list. */
1763 static Lisp_Object
1764 start_process_unwind (Lisp_Object proc)
1766 if (!PROCESSP (proc))
1767 abort ();
1769 /* Was PROC started successfully? */
1770 if (XPROCESS (proc)->pid == -1)
1771 remove_process (proc);
1773 return Qnil;
1776 static void
1777 create_process_1 (struct atimer *timer)
1779 /* Nothing to do. */
1783 void
1784 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1786 int inchannel, outchannel;
1787 pid_t pid;
1788 int sv[2];
1789 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1790 int wait_child_setup[2];
1791 #endif
1792 sigset_t procmask;
1793 sigset_t blocked;
1794 struct sigaction sigint_action;
1795 struct sigaction sigquit_action;
1796 #ifdef AIX
1797 struct sigaction sighup_action;
1798 #endif
1799 /* Use volatile to protect variables from being clobbered by longjmp. */
1800 volatile int forkin, forkout;
1801 volatile int pty_flag = 0;
1802 #ifndef USE_CRT_DLL
1803 extern char **environ;
1804 #endif
1806 inchannel = outchannel = -1;
1808 #ifdef HAVE_PTYS
1809 if (!NILP (Vprocess_connection_type))
1810 outchannel = inchannel = allocate_pty ();
1812 if (inchannel >= 0)
1814 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1815 /* On most USG systems it does not work to open the pty's tty here,
1816 then close it and reopen it in the child. */
1817 #ifdef O_NOCTTY
1818 /* Don't let this terminal become our controlling terminal
1819 (in case we don't have one). */
1820 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1821 #else
1822 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1823 #endif
1824 if (forkin < 0)
1825 report_file_error ("Opening pty", Qnil);
1826 #else
1827 forkin = forkout = -1;
1828 #endif /* not USG, or USG_SUBTTY_WORKS */
1829 pty_flag = 1;
1831 else
1832 #endif /* HAVE_PTYS */
1834 int tem;
1835 tem = pipe (sv);
1836 if (tem < 0)
1837 report_file_error ("Creating pipe", Qnil);
1838 inchannel = sv[0];
1839 forkout = sv[1];
1840 tem = pipe (sv);
1841 if (tem < 0)
1843 emacs_close (inchannel);
1844 emacs_close (forkout);
1845 report_file_error ("Creating pipe", Qnil);
1847 outchannel = sv[1];
1848 forkin = sv[0];
1851 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1853 int tem;
1855 tem = pipe (wait_child_setup);
1856 if (tem < 0)
1857 report_file_error ("Creating pipe", Qnil);
1858 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1859 if (tem >= 0)
1860 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1861 if (tem < 0)
1863 emacs_close (wait_child_setup[0]);
1864 emacs_close (wait_child_setup[1]);
1865 report_file_error ("Setting file descriptor flags", Qnil);
1868 #endif
1870 #ifdef O_NONBLOCK
1871 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1872 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1873 #else
1874 #ifdef O_NDELAY
1875 fcntl (inchannel, F_SETFL, O_NDELAY);
1876 fcntl (outchannel, F_SETFL, O_NDELAY);
1877 #endif
1878 #endif
1880 /* Record this as an active process, with its channels.
1881 As a result, child_setup will close Emacs's side of the pipes. */
1882 chan_process[inchannel] = process;
1883 XPROCESS (process)->infd = inchannel;
1884 XPROCESS (process)->outfd = outchannel;
1886 /* Previously we recorded the tty descriptor used in the subprocess.
1887 It was only used for getting the foreground tty process, so now
1888 we just reopen the device (see emacs_get_tty_pgrp) as this is
1889 more portable (see USG_SUBTTY_WORKS above). */
1891 XPROCESS (process)->pty_flag = pty_flag;
1892 XPROCESS (process)->status = Qrun;
1893 setup_process_coding_systems (process);
1895 /* Delay interrupts until we have a chance to store
1896 the new fork's pid in its process structure */
1897 sigemptyset (&blocked);
1898 #ifdef SIGCHLD
1899 sigaddset (&blocked, SIGCHLD);
1900 #endif
1901 #ifdef HAVE_WORKING_VFORK
1902 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1903 this sets the parent's signal handlers as well as the child's.
1904 So delay all interrupts whose handlers the child might munge,
1905 and record the current handlers so they can be restored later. */
1906 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1907 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1908 #ifdef AIX
1909 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1910 #endif
1911 #endif /* HAVE_WORKING_VFORK */
1912 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1914 FD_SET (inchannel, &input_wait_mask);
1915 FD_SET (inchannel, &non_keyboard_wait_mask);
1916 if (inchannel > max_process_desc)
1917 max_process_desc = inchannel;
1919 /* Until we store the proper pid, enable sigchld_handler
1920 to recognize an unknown pid as standing for this process.
1921 It is very important not to let this `marker' value stay
1922 in the table after this function has returned; if it does
1923 it might cause call-process to hang and subsequent asynchronous
1924 processes to get their return values scrambled. */
1925 XPROCESS (process)->pid = -1;
1927 BLOCK_INPUT;
1930 /* child_setup must clobber environ on systems with true vfork.
1931 Protect it from permanent change. */
1932 char **save_environ = environ;
1934 current_dir = ENCODE_FILE (current_dir);
1936 #ifndef WINDOWSNT
1937 pid = vfork ();
1938 if (pid == 0)
1939 #endif /* not WINDOWSNT */
1941 int xforkin = forkin;
1942 int xforkout = forkout;
1944 #if 0 /* This was probably a mistake--it duplicates code later on,
1945 but fails to handle all the cases. */
1946 /* Make sure SIGCHLD is not blocked in the child. */
1947 sigsetmask (SIGEMPTYMASK);
1948 #endif
1950 /* Make the pty be the controlling terminal of the process. */
1951 #ifdef HAVE_PTYS
1952 /* First, disconnect its current controlling terminal. */
1953 #ifdef HAVE_SETSID
1954 /* We tried doing setsid only if pty_flag, but it caused
1955 process_set_signal to fail on SGI when using a pipe. */
1956 setsid ();
1957 /* Make the pty's terminal the controlling terminal. */
1958 if (pty_flag && xforkin >= 0)
1960 #ifdef TIOCSCTTY
1961 /* We ignore the return value
1962 because faith@cs.unc.edu says that is necessary on Linux. */
1963 ioctl (xforkin, TIOCSCTTY, 0);
1964 #endif
1966 #else /* not HAVE_SETSID */
1967 #ifdef USG
1968 /* It's very important to call setpgrp here and no time
1969 afterwards. Otherwise, we lose our controlling tty which
1970 is set when we open the pty. */
1971 setpgrp ();
1972 #endif /* USG */
1973 #endif /* not HAVE_SETSID */
1974 #if defined (LDISC1)
1975 if (pty_flag && xforkin >= 0)
1977 struct termios t;
1978 tcgetattr (xforkin, &t);
1979 t.c_lflag = LDISC1;
1980 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1981 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1983 #else
1984 #if defined (NTTYDISC) && defined (TIOCSETD)
1985 if (pty_flag && xforkin >= 0)
1987 /* Use new line discipline. */
1988 int ldisc = NTTYDISC;
1989 ioctl (xforkin, TIOCSETD, &ldisc);
1991 #endif
1992 #endif
1993 #ifdef TIOCNOTTY
1994 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1995 can do TIOCSPGRP only to the process's controlling tty. */
1996 if (pty_flag)
1998 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1999 I can't test it since I don't have 4.3. */
2000 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2001 if (j >= 0)
2003 ioctl (j, TIOCNOTTY, 0);
2004 emacs_close (j);
2006 #ifndef USG
2007 /* In order to get a controlling terminal on some versions
2008 of BSD, it is necessary to put the process in pgrp 0
2009 before it opens the terminal. */
2010 #ifdef HAVE_SETPGID
2011 setpgid (0, 0);
2012 #else
2013 setpgrp (0, 0);
2014 #endif
2015 #endif
2017 #endif /* TIOCNOTTY */
2019 #if !defined (DONT_REOPEN_PTY)
2020 /*** There is a suggestion that this ought to be a
2021 conditional on TIOCSPGRP,
2022 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2023 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2024 that system does seem to need this code, even though
2025 both HAVE_SETSID and TIOCSCTTY are defined. */
2026 /* Now close the pty (if we had it open) and reopen it.
2027 This makes the pty the controlling terminal of the subprocess. */
2028 if (pty_flag)
2031 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2032 would work? */
2033 if (xforkin >= 0)
2034 emacs_close (xforkin);
2035 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2037 if (xforkin < 0)
2039 emacs_write (1, "Couldn't open the pty terminal ", 31);
2040 emacs_write (1, pty_name, strlen (pty_name));
2041 emacs_write (1, "\n", 1);
2042 _exit (1);
2046 #endif /* not DONT_REOPEN_PTY */
2048 #ifdef SETUP_SLAVE_PTY
2049 if (pty_flag)
2051 SETUP_SLAVE_PTY;
2053 #endif /* SETUP_SLAVE_PTY */
2054 #ifdef AIX
2055 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2056 Now reenable it in the child, so it will die when we want it to. */
2057 if (pty_flag)
2058 signal (SIGHUP, SIG_DFL);
2059 #endif
2060 #endif /* HAVE_PTYS */
2062 signal (SIGINT, SIG_DFL);
2063 signal (SIGQUIT, SIG_DFL);
2065 /* Stop blocking signals in the child. */
2066 sigprocmask (SIG_SETMASK, &procmask, 0);
2068 if (pty_flag)
2069 child_setup_tty (xforkout);
2070 #ifdef WINDOWSNT
2071 pid = child_setup (xforkin, xforkout, xforkout,
2072 new_argv, 1, current_dir);
2073 #else /* not WINDOWSNT */
2074 #ifdef FD_CLOEXEC
2075 emacs_close (wait_child_setup[0]);
2076 #endif
2077 child_setup (xforkin, xforkout, xforkout,
2078 new_argv, 1, current_dir);
2079 #endif /* not WINDOWSNT */
2081 environ = save_environ;
2084 UNBLOCK_INPUT;
2086 /* This runs in the Emacs process. */
2087 if (pid < 0)
2089 if (forkin >= 0)
2090 emacs_close (forkin);
2091 if (forkin != forkout && forkout >= 0)
2092 emacs_close (forkout);
2094 else
2096 /* vfork succeeded. */
2097 XPROCESS (process)->pid = pid;
2099 #ifdef WINDOWSNT
2100 register_child (pid, inchannel);
2101 #endif /* WINDOWSNT */
2103 /* If the subfork execv fails, and it exits,
2104 this close hangs. I don't know why.
2105 So have an interrupt jar it loose. */
2107 struct atimer *timer;
2108 EMACS_TIME offset;
2110 stop_polling ();
2111 EMACS_SET_SECS_USECS (offset, 1, 0);
2112 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2114 if (forkin >= 0)
2115 emacs_close (forkin);
2117 cancel_atimer (timer);
2118 start_polling ();
2121 if (forkin != forkout && forkout >= 0)
2122 emacs_close (forkout);
2124 #ifdef HAVE_PTYS
2125 if (pty_flag)
2126 XPROCESS (process)->tty_name = build_string (pty_name);
2127 else
2128 #endif
2129 XPROCESS (process)->tty_name = Qnil;
2131 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2132 /* Wait for child_setup to complete in case that vfork is
2133 actually defined as fork. The descriptor wait_child_setup[1]
2134 of a pipe is closed at the child side either by close-on-exec
2135 on successful execvp or the _exit call in child_setup. */
2137 char dummy;
2139 emacs_close (wait_child_setup[1]);
2140 emacs_read (wait_child_setup[0], &dummy, 1);
2141 emacs_close (wait_child_setup[0]);
2143 #endif
2146 /* Restore the signal state whether vfork succeeded or not.
2147 (We will signal an error, below, if it failed.) */
2148 #ifdef HAVE_WORKING_VFORK
2149 /* Restore the parent's signal handlers. */
2150 sigaction (SIGINT, &sigint_action, 0);
2151 sigaction (SIGQUIT, &sigquit_action, 0);
2152 #ifdef AIX
2153 sigaction (SIGHUP, &sighup_action, 0);
2154 #endif
2155 #endif /* HAVE_WORKING_VFORK */
2156 /* Stop blocking signals in the parent. */
2157 sigprocmask (SIG_SETMASK, &procmask, 0);
2159 /* Now generate the error if vfork failed. */
2160 if (pid < 0)
2161 report_file_error ("Doing vfork", Qnil);
2164 void
2165 create_pty (Lisp_Object process)
2167 int inchannel, outchannel;
2169 /* Use volatile to protect variables from being clobbered by longjmp. */
2170 volatile int forkin, forkout;
2171 volatile int pty_flag = 0;
2173 inchannel = outchannel = -1;
2175 #ifdef HAVE_PTYS
2176 if (!NILP (Vprocess_connection_type))
2177 outchannel = inchannel = allocate_pty ();
2179 if (inchannel >= 0)
2181 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2182 /* On most USG systems it does not work to open the pty's tty here,
2183 then close it and reopen it in the child. */
2184 #ifdef O_NOCTTY
2185 /* Don't let this terminal become our controlling terminal
2186 (in case we don't have one). */
2187 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2188 #else
2189 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2190 #endif
2191 if (forkin < 0)
2192 report_file_error ("Opening pty", Qnil);
2193 #if defined (DONT_REOPEN_PTY)
2194 /* In the case that vfork is defined as fork, the parent process
2195 (Emacs) may send some data before the child process completes
2196 tty options setup. So we setup tty before forking. */
2197 child_setup_tty (forkout);
2198 #endif /* DONT_REOPEN_PTY */
2199 #else
2200 forkin = forkout = -1;
2201 #endif /* not USG, or USG_SUBTTY_WORKS */
2202 pty_flag = 1;
2204 #endif /* HAVE_PTYS */
2206 #ifdef O_NONBLOCK
2207 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2208 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2209 #else
2210 #ifdef O_NDELAY
2211 fcntl (inchannel, F_SETFL, O_NDELAY);
2212 fcntl (outchannel, F_SETFL, O_NDELAY);
2213 #endif
2214 #endif
2216 /* Record this as an active process, with its channels.
2217 As a result, child_setup will close Emacs's side of the pipes. */
2218 chan_process[inchannel] = process;
2219 XPROCESS (process)->infd = inchannel;
2220 XPROCESS (process)->outfd = outchannel;
2222 /* Previously we recorded the tty descriptor used in the subprocess.
2223 It was only used for getting the foreground tty process, so now
2224 we just reopen the device (see emacs_get_tty_pgrp) as this is
2225 more portable (see USG_SUBTTY_WORKS above). */
2227 XPROCESS (process)->pty_flag = pty_flag;
2228 XPROCESS (process)->status = Qrun;
2229 setup_process_coding_systems (process);
2231 FD_SET (inchannel, &input_wait_mask);
2232 FD_SET (inchannel, &non_keyboard_wait_mask);
2233 if (inchannel > max_process_desc)
2234 max_process_desc = inchannel;
2236 XPROCESS (process)->pid = -2;
2237 #ifdef HAVE_PTYS
2238 if (pty_flag)
2239 XPROCESS (process)->tty_name = build_string (pty_name);
2240 else
2241 #endif
2242 XPROCESS (process)->tty_name = Qnil;
2246 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2247 The address family of sa is not included in the result. */
2249 static Lisp_Object
2250 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
2252 Lisp_Object address;
2253 int i;
2254 unsigned char *cp;
2255 register struct Lisp_Vector *p;
2257 /* Workaround for a bug in getsockname on BSD: Names bound to
2258 sockets in the UNIX domain are inaccessible; getsockname returns
2259 a zero length name. */
2260 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2261 return empty_unibyte_string;
2263 switch (sa->sa_family)
2265 case AF_INET:
2267 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2268 len = sizeof (sin->sin_addr) + 1;
2269 address = Fmake_vector (make_number (len), Qnil);
2270 p = XVECTOR (address);
2271 p->contents[--len] = make_number (ntohs (sin->sin_port));
2272 cp = (unsigned char *) &sin->sin_addr;
2273 break;
2275 #ifdef AF_INET6
2276 case AF_INET6:
2278 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2279 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2280 len = sizeof (sin6->sin6_addr)/2 + 1;
2281 address = Fmake_vector (make_number (len), Qnil);
2282 p = XVECTOR (address);
2283 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2284 for (i = 0; i < len; i++)
2285 p->contents[i] = make_number (ntohs (ip6[i]));
2286 return address;
2288 #endif
2289 #ifdef HAVE_LOCAL_SOCKETS
2290 case AF_LOCAL:
2292 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2293 for (i = 0; i < sizeof (sockun->sun_path); i++)
2294 if (sockun->sun_path[i] == 0)
2295 break;
2296 return make_unibyte_string (sockun->sun_path, i);
2298 #endif
2299 default:
2300 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2301 address = Fcons (make_number (sa->sa_family),
2302 Fmake_vector (make_number (len), Qnil));
2303 p = XVECTOR (XCDR (address));
2304 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2305 break;
2308 i = 0;
2309 while (i < len)
2310 p->contents[i++] = make_number (*cp++);
2312 return address;
2316 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2318 static int
2319 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2321 register struct Lisp_Vector *p;
2323 if (VECTORP (address))
2325 p = XVECTOR (address);
2326 if (p->size == 5)
2328 *familyp = AF_INET;
2329 return sizeof (struct sockaddr_in);
2331 #ifdef AF_INET6
2332 else if (p->size == 9)
2334 *familyp = AF_INET6;
2335 return sizeof (struct sockaddr_in6);
2337 #endif
2339 #ifdef HAVE_LOCAL_SOCKETS
2340 else if (STRINGP (address))
2342 *familyp = AF_LOCAL;
2343 return sizeof (struct sockaddr_un);
2345 #endif
2346 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2348 struct sockaddr *sa;
2349 *familyp = XINT (XCAR (address));
2350 p = XVECTOR (XCDR (address));
2351 return p->size + sizeof (sa->sa_family);
2353 return 0;
2356 /* Convert an address object (vector or string) to an internal sockaddr.
2358 The address format has been basically validated by
2359 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2360 it could have come from user data. So if FAMILY is not valid,
2361 we return after zeroing *SA. */
2363 static void
2364 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2366 register struct Lisp_Vector *p;
2367 register unsigned char *cp = NULL;
2368 register int i;
2370 memset (sa, 0, len);
2372 if (VECTORP (address))
2374 p = XVECTOR (address);
2375 if (family == AF_INET)
2377 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2378 len = sizeof (sin->sin_addr) + 1;
2379 i = XINT (p->contents[--len]);
2380 sin->sin_port = htons (i);
2381 cp = (unsigned char *)&sin->sin_addr;
2382 sa->sa_family = family;
2384 #ifdef AF_INET6
2385 else if (family == AF_INET6)
2387 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2388 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2389 len = sizeof (sin6->sin6_addr) + 1;
2390 i = XINT (p->contents[--len]);
2391 sin6->sin6_port = htons (i);
2392 for (i = 0; i < len; i++)
2393 if (INTEGERP (p->contents[i]))
2395 int j = XFASTINT (p->contents[i]) & 0xffff;
2396 ip6[i] = ntohs (j);
2398 sa->sa_family = family;
2399 return;
2401 #endif
2402 else
2403 return;
2405 else if (STRINGP (address))
2407 #ifdef HAVE_LOCAL_SOCKETS
2408 if (family == AF_LOCAL)
2410 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2411 cp = SDATA (address);
2412 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2413 sockun->sun_path[i] = *cp++;
2414 sa->sa_family = family;
2416 #endif
2417 return;
2419 else
2421 p = XVECTOR (XCDR (address));
2422 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2425 for (i = 0; i < len; i++)
2426 if (INTEGERP (p->contents[i]))
2427 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2430 #ifdef DATAGRAM_SOCKETS
2431 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2432 1, 1, 0,
2433 doc: /* Get the current datagram address associated with PROCESS. */)
2434 (Lisp_Object process)
2436 int channel;
2438 CHECK_PROCESS (process);
2440 if (!DATAGRAM_CONN_P (process))
2441 return Qnil;
2443 channel = XPROCESS (process)->infd;
2444 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2445 datagram_address[channel].len);
2448 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2449 2, 2, 0,
2450 doc: /* Set the datagram address for PROCESS to ADDRESS.
2451 Returns nil upon error setting address, ADDRESS otherwise. */)
2452 (Lisp_Object process, Lisp_Object address)
2454 int channel;
2455 int family, len;
2457 CHECK_PROCESS (process);
2459 if (!DATAGRAM_CONN_P (process))
2460 return Qnil;
2462 channel = XPROCESS (process)->infd;
2464 len = get_lisp_to_sockaddr_size (address, &family);
2465 if (datagram_address[channel].len != len)
2466 return Qnil;
2467 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2468 return address;
2470 #endif
2473 static const struct socket_options {
2474 /* The name of this option. Should be lowercase version of option
2475 name without SO_ prefix. */
2476 const char *name;
2477 /* Option level SOL_... */
2478 int optlevel;
2479 /* Option number SO_... */
2480 int optnum;
2481 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2482 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2483 } socket_options[] =
2485 #ifdef SO_BINDTODEVICE
2486 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2487 #endif
2488 #ifdef SO_BROADCAST
2489 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2490 #endif
2491 #ifdef SO_DONTROUTE
2492 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2493 #endif
2494 #ifdef SO_KEEPALIVE
2495 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2496 #endif
2497 #ifdef SO_LINGER
2498 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2499 #endif
2500 #ifdef SO_OOBINLINE
2501 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2502 #endif
2503 #ifdef SO_PRIORITY
2504 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2505 #endif
2506 #ifdef SO_REUSEADDR
2507 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2508 #endif
2509 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2512 /* Set option OPT to value VAL on socket S.
2514 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2515 Signals an error if setting a known option fails.
2518 static int
2519 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2521 char *name;
2522 const struct socket_options *sopt;
2523 int ret = 0;
2525 CHECK_SYMBOL (opt);
2527 name = (char *) SDATA (SYMBOL_NAME (opt));
2528 for (sopt = socket_options; sopt->name; sopt++)
2529 if (strcmp (name, sopt->name) == 0)
2530 break;
2532 switch (sopt->opttype)
2534 case SOPT_BOOL:
2536 int optval;
2537 optval = NILP (val) ? 0 : 1;
2538 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2539 &optval, sizeof (optval));
2540 break;
2543 case SOPT_INT:
2545 int optval;
2546 if (INTEGERP (val))
2547 optval = XINT (val);
2548 else
2549 error ("Bad option value for %s", name);
2550 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2551 &optval, sizeof (optval));
2552 break;
2555 #ifdef SO_BINDTODEVICE
2556 case SOPT_IFNAME:
2558 char devname[IFNAMSIZ+1];
2560 /* This is broken, at least in the Linux 2.4 kernel.
2561 To unbind, the arg must be a zero integer, not the empty string.
2562 This should work on all systems. KFS. 2003-09-23. */
2563 memset (devname, 0, sizeof devname);
2564 if (STRINGP (val))
2566 char *arg = (char *) SDATA (val);
2567 int len = min (strlen (arg), IFNAMSIZ);
2568 memcpy (devname, arg, len);
2570 else if (!NILP (val))
2571 error ("Bad option value for %s", name);
2572 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2573 devname, IFNAMSIZ);
2574 break;
2576 #endif
2578 #ifdef SO_LINGER
2579 case SOPT_LINGER:
2581 struct linger linger;
2583 linger.l_onoff = 1;
2584 linger.l_linger = 0;
2585 if (INTEGERP (val))
2586 linger.l_linger = XINT (val);
2587 else
2588 linger.l_onoff = NILP (val) ? 0 : 1;
2589 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2590 &linger, sizeof (linger));
2591 break;
2593 #endif
2595 default:
2596 return 0;
2599 if (ret < 0)
2600 report_file_error ("Cannot set network option",
2601 Fcons (opt, Fcons (val, Qnil)));
2602 return (1 << sopt->optbit);
2606 DEFUN ("set-network-process-option",
2607 Fset_network_process_option, Sset_network_process_option,
2608 3, 4, 0,
2609 doc: /* For network process PROCESS set option OPTION to value VALUE.
2610 See `make-network-process' for a list of options and values.
2611 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2612 OPTION is not a supported option, return nil instead; otherwise return t. */)
2613 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2615 int s;
2616 struct Lisp_Process *p;
2618 CHECK_PROCESS (process);
2619 p = XPROCESS (process);
2620 if (!NETCONN1_P (p))
2621 error ("Process is not a network process");
2623 s = p->infd;
2624 if (s < 0)
2625 error ("Process is not running");
2627 if (set_socket_option (s, option, value))
2629 p->childp = Fplist_put (p->childp, option, value);
2630 return Qt;
2633 if (NILP (no_error))
2634 error ("Unknown or unsupported option");
2636 return Qnil;
2640 DEFUN ("serial-process-configure",
2641 Fserial_process_configure,
2642 Sserial_process_configure,
2643 0, MANY, 0,
2644 doc: /* Configure speed, bytesize, etc. of a serial process.
2646 Arguments are specified as keyword/argument pairs. Attributes that
2647 are not given are re-initialized from the process's current
2648 configuration (available via the function `process-contact') or set to
2649 reasonable default values. The following arguments are defined:
2651 :process PROCESS
2652 :name NAME
2653 :buffer BUFFER
2654 :port PORT
2655 -- Any of these arguments can be given to identify the process that is
2656 to be configured. If none of these arguments is given, the current
2657 buffer's process is used.
2659 :speed SPEED -- SPEED is the speed of the serial port in bits per
2660 second, also called baud rate. Any value can be given for SPEED, but
2661 most serial ports work only at a few defined values between 1200 and
2662 115200, with 9600 being the most common value. If SPEED is nil, the
2663 serial port is not configured any further, i.e., all other arguments
2664 are ignored. This may be useful for special serial ports such as
2665 Bluetooth-to-serial converters which can only be configured through AT
2666 commands. A value of nil for SPEED can be used only when passed
2667 through `make-serial-process' or `serial-term'.
2669 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2670 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2672 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2673 `odd' (use odd parity), or the symbol `even' (use even parity). If
2674 PARITY is not given, no parity is used.
2676 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2677 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2678 is not given or nil, 1 stopbit is used.
2680 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2681 flowcontrol to be used, which is either nil (don't use flowcontrol),
2682 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2683 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2684 flowcontrol is used.
2686 `serial-process-configure' is called by `make-serial-process' for the
2687 initial configuration of the serial port.
2689 Examples:
2691 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2693 \(serial-process-configure
2694 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2696 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2698 usage: (serial-process-configure &rest ARGS) */)
2699 (int nargs, Lisp_Object *args)
2701 struct Lisp_Process *p;
2702 Lisp_Object contact = Qnil;
2703 Lisp_Object proc = Qnil;
2704 struct gcpro gcpro1;
2706 contact = Flist (nargs, args);
2707 GCPRO1 (contact);
2709 proc = Fplist_get (contact, QCprocess);
2710 if (NILP (proc))
2711 proc = Fplist_get (contact, QCname);
2712 if (NILP (proc))
2713 proc = Fplist_get (contact, QCbuffer);
2714 if (NILP (proc))
2715 proc = Fplist_get (contact, QCport);
2716 proc = get_process (proc);
2717 p = XPROCESS (proc);
2718 if (!EQ (p->type, Qserial))
2719 error ("Not a serial process");
2721 if (NILP (Fplist_get (p->childp, QCspeed)))
2723 UNGCPRO;
2724 return Qnil;
2727 serial_configure (p, contact);
2729 UNGCPRO;
2730 return Qnil;
2733 /* Used by make-serial-process to recover from errors. */
2734 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2736 if (!PROCESSP (proc))
2737 abort ();
2738 remove_process (proc);
2739 return Qnil;
2742 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2743 0, MANY, 0,
2744 doc: /* Create and return a serial port process.
2746 In Emacs, serial port connections are represented by process objects,
2747 so input and output work as for subprocesses, and `delete-process'
2748 closes a serial port connection. However, a serial process has no
2749 process id, it cannot be signaled, and the status codes are different
2750 from normal processes.
2752 `make-serial-process' creates a process and a buffer, on which you
2753 probably want to use `process-send-string'. Try \\[serial-term] for
2754 an interactive terminal. See below for examples.
2756 Arguments are specified as keyword/argument pairs. The following
2757 arguments are defined:
2759 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2760 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2761 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2762 the backslashes in strings).
2764 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2765 which is called by `make-serial-process'.
2767 :name NAME -- NAME is the name of the process. If NAME is not given,
2768 the value of PORT is used.
2770 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2771 with the process. Process output goes at the end of that buffer,
2772 unless you specify an output stream or filter function to handle the
2773 output. If BUFFER is not given, the value of NAME is used.
2775 :coding CODING -- If CODING is a symbol, it specifies the coding
2776 system used for both reading and writing for this process. If CODING
2777 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2778 ENCODING is used for writing.
2780 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2781 the process is running. If BOOL is not given, query before exiting.
2783 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2784 In the stopped state, a serial process does not accept incoming data,
2785 but you can send outgoing data. The stopped state is cleared by
2786 `continue-process' and set by `stop-process'.
2788 :filter FILTER -- Install FILTER as the process filter.
2790 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2792 :plist PLIST -- Install PLIST as the initial plist of the process.
2794 :speed
2795 :bytesize
2796 :parity
2797 :stopbits
2798 :flowcontrol
2799 -- These arguments are handled by `serial-process-configure', which is
2800 called by `make-serial-process'.
2802 The original argument list, possibly modified by later configuration,
2803 is available via the function `process-contact'.
2805 Examples:
2807 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2809 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2811 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2813 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2815 usage: (make-serial-process &rest ARGS) */)
2816 (int nargs, Lisp_Object *args)
2818 int fd = -1;
2819 Lisp_Object proc, contact, port;
2820 struct Lisp_Process *p;
2821 struct gcpro gcpro1;
2822 Lisp_Object name, buffer;
2823 Lisp_Object tem, val;
2824 int specpdl_count = -1;
2826 if (nargs == 0)
2827 return Qnil;
2829 contact = Flist (nargs, args);
2830 GCPRO1 (contact);
2832 port = Fplist_get (contact, QCport);
2833 if (NILP (port))
2834 error ("No port specified");
2835 CHECK_STRING (port);
2837 if (NILP (Fplist_member (contact, QCspeed)))
2838 error (":speed not specified");
2839 if (!NILP (Fplist_get (contact, QCspeed)))
2840 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2842 name = Fplist_get (contact, QCname);
2843 if (NILP (name))
2844 name = port;
2845 CHECK_STRING (name);
2846 proc = make_process (name);
2847 specpdl_count = SPECPDL_INDEX ();
2848 record_unwind_protect (make_serial_process_unwind, proc);
2849 p = XPROCESS (proc);
2851 fd = serial_open ((char*) SDATA (port));
2852 p->infd = fd;
2853 p->outfd = fd;
2854 if (fd > max_process_desc)
2855 max_process_desc = fd;
2856 chan_process[fd] = proc;
2858 buffer = Fplist_get (contact, QCbuffer);
2859 if (NILP (buffer))
2860 buffer = name;
2861 buffer = Fget_buffer_create (buffer);
2862 p->buffer = buffer;
2864 p->childp = contact;
2865 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2866 p->type = Qserial;
2867 p->sentinel = Fplist_get (contact, QCsentinel);
2868 p->filter = Fplist_get (contact, QCfilter);
2869 p->log = Qnil;
2870 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2871 p->kill_without_query = 1;
2872 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2873 p->command = Qt;
2874 p->pty_flag = 0;
2876 if (!EQ (p->command, Qt))
2878 FD_SET (fd, &input_wait_mask);
2879 FD_SET (fd, &non_keyboard_wait_mask);
2882 if (BUFFERP (buffer))
2884 set_marker_both (p->mark, buffer,
2885 BUF_ZV (XBUFFER (buffer)),
2886 BUF_ZV_BYTE (XBUFFER (buffer)));
2889 tem = Fplist_member (contact, QCcoding);
2890 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2891 tem = Qnil;
2893 val = Qnil;
2894 if (!NILP (tem))
2896 val = XCAR (XCDR (tem));
2897 if (CONSP (val))
2898 val = XCAR (val);
2900 else if (!NILP (Vcoding_system_for_read))
2901 val = Vcoding_system_for_read;
2902 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2903 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2904 val = Qnil;
2905 p->decode_coding_system = val;
2907 val = Qnil;
2908 if (!NILP (tem))
2910 val = XCAR (XCDR (tem));
2911 if (CONSP (val))
2912 val = XCDR (val);
2914 else if (!NILP (Vcoding_system_for_write))
2915 val = Vcoding_system_for_write;
2916 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2917 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2918 val = Qnil;
2919 p->encode_coding_system = val;
2921 setup_process_coding_systems (proc);
2922 p->decoding_buf = make_uninit_string (0);
2923 p->decoding_carryover = 0;
2924 p->encoding_buf = make_uninit_string (0);
2925 p->inherit_coding_system_flag
2926 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2928 Fserial_process_configure (nargs, args);
2930 specpdl_ptr = specpdl + specpdl_count;
2932 UNGCPRO;
2933 return proc;
2936 /* Create a network stream/datagram client/server process. Treated
2937 exactly like a normal process when reading and writing. Primary
2938 differences are in status display and process deletion. A network
2939 connection has no PID; you cannot signal it. All you can do is
2940 stop/continue it and deactivate/close it via delete-process */
2942 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2943 0, MANY, 0,
2944 doc: /* Create and return a network server or client process.
2946 In Emacs, network connections are represented by process objects, so
2947 input and output work as for subprocesses and `delete-process' closes
2948 a network connection. However, a network process has no process id,
2949 it cannot be signaled, and the status codes are different from normal
2950 processes.
2952 Arguments are specified as keyword/argument pairs. The following
2953 arguments are defined:
2955 :name NAME -- NAME is name for process. It is modified if necessary
2956 to make it unique.
2958 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2959 with the process. Process output goes at end of that buffer, unless
2960 you specify an output stream or filter function to handle the output.
2961 BUFFER may be also nil, meaning that this process is not associated
2962 with any buffer.
2964 :host HOST -- HOST is name of the host to connect to, or its IP
2965 address. The symbol `local' specifies the local host. If specified
2966 for a server process, it must be a valid name or address for the local
2967 host, and only clients connecting to that address will be accepted.
2969 :service SERVICE -- SERVICE is name of the service desired, or an
2970 integer specifying a port number to connect to. If SERVICE is t,
2971 a random port number is selected for the server. (If Emacs was
2972 compiled with getaddrinfo, a port number can also be specified as a
2973 string, e.g. "80", as well as an integer. This is not portable.)
2975 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2976 stream type connection, `datagram' creates a datagram type connection,
2977 `seqpacket' creates a reliable datagram connection.
2979 :family FAMILY -- FAMILY is the address (and protocol) family for the
2980 service specified by HOST and SERVICE. The default (nil) is to use
2981 whatever address family (IPv4 or IPv6) that is defined for the host
2982 and port number specified by HOST and SERVICE. Other address families
2983 supported are:
2984 local -- for a local (i.e. UNIX) address specified by SERVICE.
2985 ipv4 -- use IPv4 address family only.
2986 ipv6 -- use IPv6 address family only.
2988 :local ADDRESS -- ADDRESS is the local address used for the connection.
2989 This parameter is ignored when opening a client process. When specified
2990 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2992 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2993 connection. This parameter is ignored when opening a stream server
2994 process. For a datagram server process, it specifies the initial
2995 setting of the remote datagram address. When specified for a client
2996 process, the FAMILY, HOST, and SERVICE args are ignored.
2998 The format of ADDRESS depends on the address family:
2999 - An IPv4 address is represented as an vector of integers [A B C D P]
3000 corresponding to numeric IP address A.B.C.D and port number P.
3001 - A local address is represented as a string with the address in the
3002 local address space.
3003 - An "unsupported family" address is represented by a cons (F . AV)
3004 where F is the family number and AV is a vector containing the socket
3005 address data with one element per address data byte. Do not rely on
3006 this format in portable code, as it may depend on implementation
3007 defined constants, data sizes, and data structure alignment.
3009 :coding CODING -- If CODING is a symbol, it specifies the coding
3010 system used for both reading and writing for this process. If CODING
3011 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3012 ENCODING is used for writing.
3014 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3015 return without waiting for the connection to complete; instead, the
3016 sentinel function will be called with second arg matching "open" (if
3017 successful) or "failed" when the connect completes. Default is to use
3018 a blocking connect (i.e. wait) for stream type connections.
3020 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3021 running when Emacs is exited.
3023 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3024 In the stopped state, a server process does not accept new
3025 connections, and a client process does not handle incoming traffic.
3026 The stopped state is cleared by `continue-process' and set by
3027 `stop-process'.
3029 :filter FILTER -- Install FILTER as the process filter.
3031 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3032 process filter are multibyte, otherwise they are unibyte.
3033 If this keyword is not specified, the strings are multibyte if
3034 `default-enable-multibyte-characters' is non-nil.
3036 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3038 :log LOG -- Install LOG as the server process log function. This
3039 function is called when the server accepts a network connection from a
3040 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3041 is the server process, CLIENT is the new process for the connection,
3042 and MESSAGE is a string.
3044 :plist PLIST -- Install PLIST as the new process' initial plist.
3046 :server QLEN -- if QLEN is non-nil, create a server process for the
3047 specified FAMILY, SERVICE, and connection type (stream or datagram).
3048 If QLEN is an integer, it is used as the max. length of the server's
3049 pending connection queue (also known as the backlog); the default
3050 queue length is 5. Default is to create a client process.
3052 The following network options can be specified for this connection:
3054 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3055 :dontroute BOOL -- Only send to directly connected hosts.
3056 :keepalive BOOL -- Send keep-alive messages on network stream.
3057 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3058 :oobinline BOOL -- Place out-of-band data in receive data stream.
3059 :priority INT -- Set protocol defined priority for sent packets.
3060 :reuseaddr BOOL -- Allow reusing a recently used local address
3061 (this is allowed by default for a server process).
3062 :bindtodevice NAME -- bind to interface NAME. Using this may require
3063 special privileges on some systems.
3065 Consult the relevant system programmer's manual pages for more
3066 information on using these options.
3069 A server process will listen for and accept connections from clients.
3070 When a client connection is accepted, a new network process is created
3071 for the connection with the following parameters:
3073 - The client's process name is constructed by concatenating the server
3074 process' NAME and a client identification string.
3075 - If the FILTER argument is non-nil, the client process will not get a
3076 separate process buffer; otherwise, the client's process buffer is a newly
3077 created buffer named after the server process' BUFFER name or process
3078 NAME concatenated with the client identification string.
3079 - The connection type and the process filter and sentinel parameters are
3080 inherited from the server process' TYPE, FILTER and SENTINEL.
3081 - The client process' contact info is set according to the client's
3082 addressing information (typically an IP address and a port number).
3083 - The client process' plist is initialized from the server's plist.
3085 Notice that the FILTER and SENTINEL args are never used directly by
3086 the server process. Also, the BUFFER argument is not used directly by
3087 the server process, but via the optional :log function, accepted (and
3088 failed) connections may be logged in the server process' buffer.
3090 The original argument list, modified with the actual connection
3091 information, is available via the `process-contact' function.
3093 usage: (make-network-process &rest ARGS) */)
3094 (int nargs, Lisp_Object *args)
3096 Lisp_Object proc;
3097 Lisp_Object contact;
3098 struct Lisp_Process *p;
3099 #ifdef HAVE_GETADDRINFO
3100 struct addrinfo ai, *res, *lres;
3101 struct addrinfo hints;
3102 const char *portstring;
3103 char portbuf[128];
3104 #else /* HAVE_GETADDRINFO */
3105 struct _emacs_addrinfo
3107 int ai_family;
3108 int ai_socktype;
3109 int ai_protocol;
3110 int ai_addrlen;
3111 struct sockaddr *ai_addr;
3112 struct _emacs_addrinfo *ai_next;
3113 } ai, *res, *lres;
3114 #endif /* HAVE_GETADDRINFO */
3115 struct sockaddr_in address_in;
3116 #ifdef HAVE_LOCAL_SOCKETS
3117 struct sockaddr_un address_un;
3118 #endif
3119 int port;
3120 int ret = 0;
3121 int xerrno = 0;
3122 int s = -1, outch, inch;
3123 struct gcpro gcpro1;
3124 int count = SPECPDL_INDEX ();
3125 int count1;
3126 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3127 Lisp_Object tem;
3128 Lisp_Object name, buffer, host, service, address;
3129 Lisp_Object filter, sentinel;
3130 int is_non_blocking_client = 0;
3131 int is_server = 0, backlog = 5;
3132 int socktype;
3133 int family = -1;
3135 if (nargs == 0)
3136 return Qnil;
3138 /* Save arguments for process-contact and clone-process. */
3139 contact = Flist (nargs, args);
3140 GCPRO1 (contact);
3142 #ifdef WINDOWSNT
3143 /* Ensure socket support is loaded if available. */
3144 init_winsock (TRUE);
3145 #endif
3147 /* :type TYPE (nil: stream, datagram */
3148 tem = Fplist_get (contact, QCtype);
3149 if (NILP (tem))
3150 socktype = SOCK_STREAM;
3151 #ifdef DATAGRAM_SOCKETS
3152 else if (EQ (tem, Qdatagram))
3153 socktype = SOCK_DGRAM;
3154 #endif
3155 #ifdef HAVE_SEQPACKET
3156 else if (EQ (tem, Qseqpacket))
3157 socktype = SOCK_SEQPACKET;
3158 #endif
3159 else
3160 error ("Unsupported connection type");
3162 /* :server BOOL */
3163 tem = Fplist_get (contact, QCserver);
3164 if (!NILP (tem))
3166 /* Don't support network sockets when non-blocking mode is
3167 not available, since a blocked Emacs is not useful. */
3168 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3169 error ("Network servers not supported");
3170 #else
3171 is_server = 1;
3172 if (INTEGERP (tem))
3173 backlog = XINT (tem);
3174 #endif
3177 /* Make QCaddress an alias for :local (server) or :remote (client). */
3178 QCaddress = is_server ? QClocal : QCremote;
3180 /* :nowait BOOL */
3181 if (!is_server && socktype != SOCK_DGRAM
3182 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3184 #ifndef NON_BLOCKING_CONNECT
3185 error ("Non-blocking connect not supported");
3186 #else
3187 is_non_blocking_client = 1;
3188 #endif
3191 name = Fplist_get (contact, QCname);
3192 buffer = Fplist_get (contact, QCbuffer);
3193 filter = Fplist_get (contact, QCfilter);
3194 sentinel = Fplist_get (contact, QCsentinel);
3196 CHECK_STRING (name);
3198 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3199 ai.ai_socktype = socktype;
3200 ai.ai_protocol = 0;
3201 ai.ai_next = NULL;
3202 res = &ai;
3204 /* :local ADDRESS or :remote ADDRESS */
3205 address = Fplist_get (contact, QCaddress);
3206 if (!NILP (address))
3208 host = service = Qnil;
3210 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3211 error ("Malformed :address");
3212 ai.ai_family = family;
3213 ai.ai_addr = alloca (ai.ai_addrlen);
3214 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3215 goto open_socket;
3218 /* :family FAMILY -- nil (for Inet), local, or integer. */
3219 tem = Fplist_get (contact, QCfamily);
3220 if (NILP (tem))
3222 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3223 family = AF_UNSPEC;
3224 #else
3225 family = AF_INET;
3226 #endif
3228 #ifdef HAVE_LOCAL_SOCKETS
3229 else if (EQ (tem, Qlocal))
3230 family = AF_LOCAL;
3231 #endif
3232 #ifdef AF_INET6
3233 else if (EQ (tem, Qipv6))
3234 family = AF_INET6;
3235 #endif
3236 else if (EQ (tem, Qipv4))
3237 family = AF_INET;
3238 else if (INTEGERP (tem))
3239 family = XINT (tem);
3240 else
3241 error ("Unknown address family");
3243 ai.ai_family = family;
3245 /* :service SERVICE -- string, integer (port number), or t (random port). */
3246 service = Fplist_get (contact, QCservice);
3248 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3249 host = Fplist_get (contact, QChost);
3250 if (!NILP (host))
3252 if (EQ (host, Qlocal))
3253 /* Depending on setup, "localhost" may map to different IPv4 and/or
3254 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
3255 host = build_string ("127.0.0.1");
3256 CHECK_STRING (host);
3259 #ifdef HAVE_LOCAL_SOCKETS
3260 if (family == AF_LOCAL)
3262 if (!NILP (host))
3264 message (":family local ignores the :host \"%s\" property",
3265 SDATA (host));
3266 contact = Fplist_put (contact, QChost, Qnil);
3267 host = Qnil;
3269 CHECK_STRING (service);
3270 memset (&address_un, 0, sizeof address_un);
3271 address_un.sun_family = AF_LOCAL;
3272 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3273 ai.ai_addr = (struct sockaddr *) &address_un;
3274 ai.ai_addrlen = sizeof address_un;
3275 goto open_socket;
3277 #endif
3279 /* Slow down polling to every ten seconds.
3280 Some kernels have a bug which causes retrying connect to fail
3281 after a connect. Polling can interfere with gethostbyname too. */
3282 #ifdef POLL_FOR_INPUT
3283 if (socktype != SOCK_DGRAM)
3285 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3286 bind_polling_period (10);
3288 #endif
3290 #ifdef HAVE_GETADDRINFO
3291 /* If we have a host, use getaddrinfo to resolve both host and service.
3292 Otherwise, use getservbyname to lookup the service. */
3293 if (!NILP (host))
3296 /* SERVICE can either be a string or int.
3297 Convert to a C string for later use by getaddrinfo. */
3298 if (EQ (service, Qt))
3299 portstring = "0";
3300 else if (INTEGERP (service))
3302 sprintf (portbuf, "%ld", (long) XINT (service));
3303 portstring = portbuf;
3305 else
3307 CHECK_STRING (service);
3308 portstring = SDATA (service);
3311 immediate_quit = 1;
3312 QUIT;
3313 memset (&hints, 0, sizeof (hints));
3314 hints.ai_flags = 0;
3315 hints.ai_family = family;
3316 hints.ai_socktype = socktype;
3317 hints.ai_protocol = 0;
3319 #ifdef HAVE_RES_INIT
3320 res_init ();
3321 #endif
3323 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3324 if (ret)
3325 #ifdef HAVE_GAI_STRERROR
3326 error ("%s/%s %s", SDATA (host), portstring, gai_strerror (ret));
3327 #else
3328 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3329 #endif
3330 immediate_quit = 0;
3332 goto open_socket;
3334 #endif /* HAVE_GETADDRINFO */
3336 /* We end up here if getaddrinfo is not defined, or in case no hostname
3337 has been specified (e.g. for a local server process). */
3339 if (EQ (service, Qt))
3340 port = 0;
3341 else if (INTEGERP (service))
3342 port = htons ((unsigned short) XINT (service));
3343 else
3345 struct servent *svc_info;
3346 CHECK_STRING (service);
3347 svc_info = getservbyname (SDATA (service),
3348 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3349 if (svc_info == 0)
3350 error ("Unknown service: %s", SDATA (service));
3351 port = svc_info->s_port;
3354 memset (&address_in, 0, sizeof address_in);
3355 address_in.sin_family = family;
3356 address_in.sin_addr.s_addr = INADDR_ANY;
3357 address_in.sin_port = port;
3359 #ifndef HAVE_GETADDRINFO
3360 if (!NILP (host))
3362 struct hostent *host_info_ptr;
3364 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3365 as it may `hang' Emacs for a very long time. */
3366 immediate_quit = 1;
3367 QUIT;
3369 #ifdef HAVE_RES_INIT
3370 res_init ();
3371 #endif
3373 host_info_ptr = gethostbyname (SDATA (host));
3374 immediate_quit = 0;
3376 if (host_info_ptr)
3378 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3379 host_info_ptr->h_length);
3380 family = host_info_ptr->h_addrtype;
3381 address_in.sin_family = family;
3383 else
3384 /* Attempt to interpret host as numeric inet address */
3386 unsigned long numeric_addr;
3387 numeric_addr = inet_addr ((char *) SDATA (host));
3388 if (numeric_addr == -1)
3389 error ("Unknown host \"%s\"", SDATA (host));
3391 memcpy (&address_in.sin_addr, &numeric_addr,
3392 sizeof (address_in.sin_addr));
3396 #endif /* not HAVE_GETADDRINFO */
3398 ai.ai_family = family;
3399 ai.ai_addr = (struct sockaddr *) &address_in;
3400 ai.ai_addrlen = sizeof address_in;
3402 open_socket:
3404 /* Do this in case we never enter the for-loop below. */
3405 count1 = SPECPDL_INDEX ();
3406 s = -1;
3408 for (lres = res; lres; lres = lres->ai_next)
3410 int optn, optbits;
3412 retry_connect:
3414 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3415 if (s < 0)
3417 xerrno = errno;
3418 continue;
3421 #ifdef DATAGRAM_SOCKETS
3422 if (!is_server && socktype == SOCK_DGRAM)
3423 break;
3424 #endif /* DATAGRAM_SOCKETS */
3426 #ifdef NON_BLOCKING_CONNECT
3427 if (is_non_blocking_client)
3429 #ifdef O_NONBLOCK
3430 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3431 #else
3432 ret = fcntl (s, F_SETFL, O_NDELAY);
3433 #endif
3434 if (ret < 0)
3436 xerrno = errno;
3437 emacs_close (s);
3438 s = -1;
3439 continue;
3442 #endif
3444 /* Make us close S if quit. */
3445 record_unwind_protect (close_file_unwind, make_number (s));
3447 /* Parse network options in the arg list.
3448 We simply ignore anything which isn't a known option (including other keywords).
3449 An error is signaled if setting a known option fails. */
3450 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3451 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3453 if (is_server)
3455 /* Configure as a server socket. */
3457 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3458 explicit :reuseaddr key to override this. */
3459 #ifdef HAVE_LOCAL_SOCKETS
3460 if (family != AF_LOCAL)
3461 #endif
3462 if (!(optbits & (1 << OPIX_REUSEADDR)))
3464 int optval = 1;
3465 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3466 report_file_error ("Cannot set reuse option on server socket", Qnil);
3469 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3470 report_file_error ("Cannot bind server socket", Qnil);
3472 #ifdef HAVE_GETSOCKNAME
3473 if (EQ (service, Qt))
3475 struct sockaddr_in sa1;
3476 int len1 = sizeof (sa1);
3477 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3479 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3480 service = make_number (ntohs (sa1.sin_port));
3481 contact = Fplist_put (contact, QCservice, service);
3484 #endif
3486 if (socktype != SOCK_DGRAM && listen (s, backlog))
3487 report_file_error ("Cannot listen on server socket", Qnil);
3489 break;
3492 immediate_quit = 1;
3493 QUIT;
3495 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3496 xerrno = errno;
3498 if (ret == 0 || xerrno == EISCONN)
3500 /* The unwind-protect will be discarded afterwards.
3501 Likewise for immediate_quit. */
3502 break;
3505 #ifdef NON_BLOCKING_CONNECT
3506 #ifdef EINPROGRESS
3507 if (is_non_blocking_client && xerrno == EINPROGRESS)
3508 break;
3509 #else
3510 #ifdef EWOULDBLOCK
3511 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3512 break;
3513 #endif
3514 #endif
3515 #endif
3517 #ifndef WINDOWSNT
3518 if (xerrno == EINTR)
3520 /* Unlike most other syscalls connect() cannot be called
3521 again. (That would return EALREADY.) The proper way to
3522 wait for completion is select(). */
3523 int sc, len;
3524 SELECT_TYPE fdset;
3525 retry_select:
3526 FD_ZERO (&fdset);
3527 FD_SET (s, &fdset);
3528 QUIT;
3529 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3530 (EMACS_TIME *)0);
3531 if (sc == -1)
3533 if (errno == EINTR)
3534 goto retry_select;
3535 else
3536 report_file_error ("select failed", Qnil);
3538 eassert (sc > 0);
3540 len = sizeof xerrno;
3541 eassert (FD_ISSET (s, &fdset));
3542 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3543 report_file_error ("getsockopt failed", Qnil);
3544 if (xerrno)
3545 errno = xerrno, report_file_error ("error during connect", Qnil);
3546 else
3547 break;
3549 #endif /* !WINDOWSNT */
3551 immediate_quit = 0;
3553 /* Discard the unwind protect closing S. */
3554 specpdl_ptr = specpdl + count1;
3555 emacs_close (s);
3556 s = -1;
3558 #ifdef WINDOWSNT
3559 if (xerrno == EINTR)
3560 goto retry_connect;
3561 #endif
3564 if (s >= 0)
3566 #ifdef DATAGRAM_SOCKETS
3567 if (socktype == SOCK_DGRAM)
3569 if (datagram_address[s].sa)
3570 abort ();
3571 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3572 datagram_address[s].len = lres->ai_addrlen;
3573 if (is_server)
3575 Lisp_Object remote;
3576 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3577 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3579 int rfamily, rlen;
3580 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3581 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3582 conv_lisp_to_sockaddr (rfamily, remote,
3583 datagram_address[s].sa, rlen);
3586 else
3587 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3589 #endif
3590 contact = Fplist_put (contact, QCaddress,
3591 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3592 #ifdef HAVE_GETSOCKNAME
3593 if (!is_server)
3595 struct sockaddr_in sa1;
3596 int len1 = sizeof (sa1);
3597 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3598 contact = Fplist_put (contact, QClocal,
3599 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3601 #endif
3604 immediate_quit = 0;
3606 #ifdef HAVE_GETADDRINFO
3607 if (res != &ai)
3609 BLOCK_INPUT;
3610 freeaddrinfo (res);
3611 UNBLOCK_INPUT;
3613 #endif
3615 /* Discard the unwind protect for closing S, if any. */
3616 specpdl_ptr = specpdl + count1;
3618 /* Unwind bind_polling_period and request_sigio. */
3619 unbind_to (count, Qnil);
3621 if (s < 0)
3623 /* If non-blocking got this far - and failed - assume non-blocking is
3624 not supported after all. This is probably a wrong assumption, but
3625 the normal blocking calls to open-network-stream handles this error
3626 better. */
3627 if (is_non_blocking_client)
3628 return Qnil;
3630 errno = xerrno;
3631 if (is_server)
3632 report_file_error ("make server process failed", contact);
3633 else
3634 report_file_error ("make client process failed", contact);
3637 inch = s;
3638 outch = s;
3640 if (!NILP (buffer))
3641 buffer = Fget_buffer_create (buffer);
3642 proc = make_process (name);
3644 chan_process[inch] = proc;
3646 #ifdef O_NONBLOCK
3647 fcntl (inch, F_SETFL, O_NONBLOCK);
3648 #else
3649 #ifdef O_NDELAY
3650 fcntl (inch, F_SETFL, O_NDELAY);
3651 #endif
3652 #endif
3654 p = XPROCESS (proc);
3656 p->childp = contact;
3657 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3658 p->type = Qnetwork;
3660 p->buffer = buffer;
3661 p->sentinel = sentinel;
3662 p->filter = filter;
3663 p->log = Fplist_get (contact, QClog);
3664 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3665 p->kill_without_query = 1;
3666 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3667 p->command = Qt;
3668 p->pid = 0;
3669 p->infd = inch;
3670 p->outfd = outch;
3671 if (is_server && socktype != SOCK_DGRAM)
3672 p->status = Qlisten;
3674 /* Make the process marker point into the process buffer (if any). */
3675 if (BUFFERP (buffer))
3676 set_marker_both (p->mark, buffer,
3677 BUF_ZV (XBUFFER (buffer)),
3678 BUF_ZV_BYTE (XBUFFER (buffer)));
3680 #ifdef NON_BLOCKING_CONNECT
3681 if (is_non_blocking_client)
3683 /* We may get here if connect did succeed immediately. However,
3684 in that case, we still need to signal this like a non-blocking
3685 connection. */
3686 p->status = Qconnect;
3687 if (!FD_ISSET (inch, &connect_wait_mask))
3689 FD_SET (inch, &connect_wait_mask);
3690 FD_SET (inch, &write_mask);
3691 num_pending_connects++;
3694 else
3695 #endif
3696 /* A server may have a client filter setting of Qt, but it must
3697 still listen for incoming connects unless it is stopped. */
3698 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3699 || (EQ (p->status, Qlisten) && NILP (p->command)))
3701 FD_SET (inch, &input_wait_mask);
3702 FD_SET (inch, &non_keyboard_wait_mask);
3705 if (inch > max_process_desc)
3706 max_process_desc = inch;
3708 tem = Fplist_member (contact, QCcoding);
3709 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3710 tem = Qnil; /* No error message (too late!). */
3713 /* Setup coding systems for communicating with the network stream. */
3714 struct gcpro gcpro1;
3715 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3716 Lisp_Object coding_systems = Qt;
3717 Lisp_Object args[5], val;
3719 if (!NILP (tem))
3721 val = XCAR (XCDR (tem));
3722 if (CONSP (val))
3723 val = XCAR (val);
3725 else if (!NILP (Vcoding_system_for_read))
3726 val = Vcoding_system_for_read;
3727 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3728 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3729 /* We dare not decode end-of-line format by setting VAL to
3730 Qraw_text, because the existing Emacs Lisp libraries
3731 assume that they receive bare code including a sequene of
3732 CR LF. */
3733 val = Qnil;
3734 else
3736 if (NILP (host) || NILP (service))
3737 coding_systems = Qnil;
3738 else
3740 args[0] = Qopen_network_stream, args[1] = name,
3741 args[2] = buffer, args[3] = host, args[4] = service;
3742 GCPRO1 (proc);
3743 coding_systems = Ffind_operation_coding_system (5, args);
3744 UNGCPRO;
3746 if (CONSP (coding_systems))
3747 val = XCAR (coding_systems);
3748 else if (CONSP (Vdefault_process_coding_system))
3749 val = XCAR (Vdefault_process_coding_system);
3750 else
3751 val = Qnil;
3753 p->decode_coding_system = val;
3755 if (!NILP (tem))
3757 val = XCAR (XCDR (tem));
3758 if (CONSP (val))
3759 val = XCDR (val);
3761 else if (!NILP (Vcoding_system_for_write))
3762 val = Vcoding_system_for_write;
3763 else if (NILP (current_buffer->enable_multibyte_characters))
3764 val = Qnil;
3765 else
3767 if (EQ (coding_systems, Qt))
3769 if (NILP (host) || NILP (service))
3770 coding_systems = Qnil;
3771 else
3773 args[0] = Qopen_network_stream, args[1] = name,
3774 args[2] = buffer, args[3] = host, args[4] = service;
3775 GCPRO1 (proc);
3776 coding_systems = Ffind_operation_coding_system (5, args);
3777 UNGCPRO;
3780 if (CONSP (coding_systems))
3781 val = XCDR (coding_systems);
3782 else if (CONSP (Vdefault_process_coding_system))
3783 val = XCDR (Vdefault_process_coding_system);
3784 else
3785 val = Qnil;
3787 p->encode_coding_system = val;
3789 setup_process_coding_systems (proc);
3791 p->decoding_buf = make_uninit_string (0);
3792 p->decoding_carryover = 0;
3793 p->encoding_buf = make_uninit_string (0);
3795 p->inherit_coding_system_flag
3796 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3798 UNGCPRO;
3799 return proc;
3803 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3805 #ifdef SIOCGIFCONF
3806 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3807 doc: /* Return an alist of all network interfaces and their network address.
3808 Each element is a cons, the car of which is a string containing the
3809 interface name, and the cdr is the network address in internal
3810 format; see the description of ADDRESS in `make-network-process'. */)
3811 (void)
3813 struct ifconf ifconf;
3814 struct ifreq *ifreqs = NULL;
3815 int ifaces = 0;
3816 int buf_size, s;
3817 Lisp_Object res;
3819 s = socket (AF_INET, SOCK_STREAM, 0);
3820 if (s < 0)
3821 return Qnil;
3823 again:
3824 ifaces += 25;
3825 buf_size = ifaces * sizeof (ifreqs[0]);
3826 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3827 if (!ifreqs)
3829 close (s);
3830 return Qnil;
3833 ifconf.ifc_len = buf_size;
3834 ifconf.ifc_req = ifreqs;
3835 if (ioctl (s, SIOCGIFCONF, &ifconf))
3837 close (s);
3838 return Qnil;
3841 if (ifconf.ifc_len == buf_size)
3842 goto again;
3844 close (s);
3845 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3847 res = Qnil;
3848 while (--ifaces >= 0)
3850 struct ifreq *ifq = &ifreqs[ifaces];
3851 char namebuf[sizeof (ifq->ifr_name) + 1];
3852 if (ifq->ifr_addr.sa_family != AF_INET)
3853 continue;
3854 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3855 namebuf[sizeof (ifq->ifr_name)] = 0;
3856 res = Fcons (Fcons (build_string (namebuf),
3857 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3858 sizeof (struct sockaddr))),
3859 res);
3862 return res;
3864 #endif /* SIOCGIFCONF */
3866 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3868 struct ifflag_def {
3869 int flag_bit;
3870 const char *flag_sym;
3873 static const struct ifflag_def ifflag_table[] = {
3874 #ifdef IFF_UP
3875 { IFF_UP, "up" },
3876 #endif
3877 #ifdef IFF_BROADCAST
3878 { IFF_BROADCAST, "broadcast" },
3879 #endif
3880 #ifdef IFF_DEBUG
3881 { IFF_DEBUG, "debug" },
3882 #endif
3883 #ifdef IFF_LOOPBACK
3884 { IFF_LOOPBACK, "loopback" },
3885 #endif
3886 #ifdef IFF_POINTOPOINT
3887 { IFF_POINTOPOINT, "pointopoint" },
3888 #endif
3889 #ifdef IFF_RUNNING
3890 { IFF_RUNNING, "running" },
3891 #endif
3892 #ifdef IFF_NOARP
3893 { IFF_NOARP, "noarp" },
3894 #endif
3895 #ifdef IFF_PROMISC
3896 { IFF_PROMISC, "promisc" },
3897 #endif
3898 #ifdef IFF_NOTRAILERS
3899 { IFF_NOTRAILERS, "notrailers" },
3900 #endif
3901 #ifdef IFF_ALLMULTI
3902 { IFF_ALLMULTI, "allmulti" },
3903 #endif
3904 #ifdef IFF_MASTER
3905 { IFF_MASTER, "master" },
3906 #endif
3907 #ifdef IFF_SLAVE
3908 { IFF_SLAVE, "slave" },
3909 #endif
3910 #ifdef IFF_MULTICAST
3911 { IFF_MULTICAST, "multicast" },
3912 #endif
3913 #ifdef IFF_PORTSEL
3914 { IFF_PORTSEL, "portsel" },
3915 #endif
3916 #ifdef IFF_AUTOMEDIA
3917 { IFF_AUTOMEDIA, "automedia" },
3918 #endif
3919 #ifdef IFF_DYNAMIC
3920 { IFF_DYNAMIC, "dynamic" },
3921 #endif
3922 #ifdef IFF_OACTIVE
3923 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3924 #endif
3925 #ifdef IFF_SIMPLEX
3926 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3927 #endif
3928 #ifdef IFF_LINK0
3929 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3930 #endif
3931 #ifdef IFF_LINK1
3932 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3933 #endif
3934 #ifdef IFF_LINK2
3935 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3936 #endif
3937 { 0, 0 }
3940 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3941 doc: /* Return information about network interface named IFNAME.
3942 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3943 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3944 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3945 FLAGS is the current flags of the interface. */)
3946 (Lisp_Object ifname)
3948 struct ifreq rq;
3949 Lisp_Object res = Qnil;
3950 Lisp_Object elt;
3951 int s;
3952 int any = 0;
3954 CHECK_STRING (ifname);
3956 memset (rq.ifr_name, 0, sizeof rq.ifr_name);
3957 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3959 s = socket (AF_INET, SOCK_STREAM, 0);
3960 if (s < 0)
3961 return Qnil;
3963 elt = Qnil;
3964 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3965 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3967 int flags = rq.ifr_flags;
3968 const struct ifflag_def *fp;
3969 int fnum;
3971 any++;
3972 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3974 if (flags & fp->flag_bit)
3976 elt = Fcons (intern (fp->flag_sym), elt);
3977 flags -= fp->flag_bit;
3980 for (fnum = 0; flags && fnum < 32; fnum++)
3982 if (flags & (1 << fnum))
3984 elt = Fcons (make_number (fnum), elt);
3988 #endif
3989 res = Fcons (elt, res);
3991 elt = Qnil;
3992 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
3993 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3995 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3996 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3997 int n;
3999 any++;
4000 for (n = 0; n < 6; n++)
4001 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4002 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4004 #endif
4005 res = Fcons (elt, res);
4007 elt = Qnil;
4008 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4009 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4011 any++;
4012 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4013 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4014 #else
4015 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4016 #endif
4018 #endif
4019 res = Fcons (elt, res);
4021 elt = Qnil;
4022 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4023 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4025 any++;
4026 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4028 #endif
4029 res = Fcons (elt, res);
4031 elt = Qnil;
4032 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4033 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4035 any++;
4036 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4038 #endif
4039 res = Fcons (elt, res);
4041 close (s);
4043 return any ? res : Qnil;
4045 #endif
4046 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
4048 /* Turn off input and output for process PROC. */
4050 void
4051 deactivate_process (Lisp_Object proc)
4053 register int inchannel, outchannel;
4054 register struct Lisp_Process *p = XPROCESS (proc);
4056 inchannel = p->infd;
4057 outchannel = p->outfd;
4059 #ifdef ADAPTIVE_READ_BUFFERING
4060 if (p->read_output_delay > 0)
4062 if (--process_output_delay_count < 0)
4063 process_output_delay_count = 0;
4064 p->read_output_delay = 0;
4065 p->read_output_skip = 0;
4067 #endif
4069 if (inchannel >= 0)
4071 /* Beware SIGCHLD hereabouts. */
4072 flush_pending_output (inchannel);
4073 emacs_close (inchannel);
4074 if (outchannel >= 0 && outchannel != inchannel)
4075 emacs_close (outchannel);
4077 p->infd = -1;
4078 p->outfd = -1;
4079 #ifdef DATAGRAM_SOCKETS
4080 if (DATAGRAM_CHAN_P (inchannel))
4082 xfree (datagram_address[inchannel].sa);
4083 datagram_address[inchannel].sa = 0;
4084 datagram_address[inchannel].len = 0;
4086 #endif
4087 chan_process[inchannel] = Qnil;
4088 FD_CLR (inchannel, &input_wait_mask);
4089 FD_CLR (inchannel, &non_keyboard_wait_mask);
4090 #ifdef NON_BLOCKING_CONNECT
4091 if (FD_ISSET (inchannel, &connect_wait_mask))
4093 FD_CLR (inchannel, &connect_wait_mask);
4094 FD_CLR (inchannel, &write_mask);
4095 if (--num_pending_connects < 0)
4096 abort ();
4098 #endif
4099 if (inchannel == max_process_desc)
4101 int i;
4102 /* We just closed the highest-numbered process input descriptor,
4103 so recompute the highest-numbered one now. */
4104 max_process_desc = 0;
4105 for (i = 0; i < MAXDESC; i++)
4106 if (!NILP (chan_process[i]))
4107 max_process_desc = i;
4113 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4114 0, 4, 0,
4115 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4116 It is read into the process' buffers or given to their filter functions.
4117 Non-nil arg PROCESS means do not return until some output has been received
4118 from PROCESS.
4120 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4121 and milliseconds to wait; return after that much time whether or not
4122 there is any subprocess output. If SECONDS is a floating point number,
4123 it specifies a fractional number of seconds to wait.
4124 The MILLISEC argument is obsolete and should be avoided.
4126 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4127 from PROCESS, suspending reading output from other processes.
4128 If JUST-THIS-ONE is an integer, don't run any timers either.
4129 Return non-nil if we received any output before the timeout expired. */)
4130 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
4132 int secs, usecs = 0;
4134 if (! NILP (process))
4135 CHECK_PROCESS (process);
4136 else
4137 just_this_one = Qnil;
4139 if (!NILP (millisec))
4140 { /* Obsolete calling convention using integers rather than floats. */
4141 CHECK_NUMBER (millisec);
4142 if (NILP (seconds))
4143 seconds = make_float (XINT (millisec) / 1000.0);
4144 else
4146 CHECK_NUMBER (seconds);
4147 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4151 if (!NILP (seconds))
4153 if (INTEGERP (seconds))
4154 secs = XINT (seconds);
4155 else if (FLOATP (seconds))
4157 double timeout = XFLOAT_DATA (seconds);
4158 secs = (int) timeout;
4159 usecs = (int) ((timeout - (double) secs) * 1000000);
4161 else
4162 wrong_type_argument (Qnumberp, seconds);
4164 if (secs < 0 || (secs == 0 && usecs == 0))
4165 secs = -1, usecs = 0;
4167 else
4168 secs = NILP (process) ? -1 : 0;
4170 return
4171 (wait_reading_process_output (secs, usecs, 0, 0,
4172 Qnil,
4173 !NILP (process) ? XPROCESS (process) : NULL,
4174 NILP (just_this_one) ? 0 :
4175 !INTEGERP (just_this_one) ? 1 : -1)
4176 ? Qt : Qnil);
4179 /* Accept a connection for server process SERVER on CHANNEL. */
4181 static int connect_counter = 0;
4183 static void
4184 server_accept_connection (Lisp_Object server, int channel)
4186 Lisp_Object proc, caller, name, buffer;
4187 Lisp_Object contact, host, service;
4188 struct Lisp_Process *ps= XPROCESS (server);
4189 struct Lisp_Process *p;
4190 int s;
4191 union u_sockaddr {
4192 struct sockaddr sa;
4193 struct sockaddr_in in;
4194 #ifdef AF_INET6
4195 struct sockaddr_in6 in6;
4196 #endif
4197 #ifdef HAVE_LOCAL_SOCKETS
4198 struct sockaddr_un un;
4199 #endif
4200 } saddr;
4201 int len = sizeof saddr;
4203 s = accept (channel, &saddr.sa, &len);
4205 if (s < 0)
4207 int code = errno;
4209 if (code == EAGAIN)
4210 return;
4211 #ifdef EWOULDBLOCK
4212 if (code == EWOULDBLOCK)
4213 return;
4214 #endif
4216 if (!NILP (ps->log))
4217 call3 (ps->log, server, Qnil,
4218 concat3 (build_string ("accept failed with code"),
4219 Fnumber_to_string (make_number (code)),
4220 build_string ("\n")));
4221 return;
4224 connect_counter++;
4226 /* Setup a new process to handle the connection. */
4228 /* Generate a unique identification of the caller, and build contact
4229 information for this process. */
4230 host = Qt;
4231 service = Qnil;
4232 switch (saddr.sa.sa_family)
4234 case AF_INET:
4236 Lisp_Object args[5];
4237 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4238 args[0] = build_string ("%d.%d.%d.%d");
4239 args[1] = make_number (*ip++);
4240 args[2] = make_number (*ip++);
4241 args[3] = make_number (*ip++);
4242 args[4] = make_number (*ip++);
4243 host = Fformat (5, args);
4244 service = make_number (ntohs (saddr.in.sin_port));
4246 args[0] = build_string (" <%s:%d>");
4247 args[1] = host;
4248 args[2] = service;
4249 caller = Fformat (3, args);
4251 break;
4253 #ifdef AF_INET6
4254 case AF_INET6:
4256 Lisp_Object args[9];
4257 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4258 int i;
4259 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4260 for (i = 0; i < 8; i++)
4261 args[i+1] = make_number (ntohs (ip6[i]));
4262 host = Fformat (9, args);
4263 service = make_number (ntohs (saddr.in.sin_port));
4265 args[0] = build_string (" <[%s]:%d>");
4266 args[1] = host;
4267 args[2] = service;
4268 caller = Fformat (3, args);
4270 break;
4271 #endif
4273 #ifdef HAVE_LOCAL_SOCKETS
4274 case AF_LOCAL:
4275 #endif
4276 default:
4277 caller = Fnumber_to_string (make_number (connect_counter));
4278 caller = concat3 (build_string (" <"), caller, build_string (">"));
4279 break;
4282 /* Create a new buffer name for this process if it doesn't have a
4283 filter. The new buffer name is based on the buffer name or
4284 process name of the server process concatenated with the caller
4285 identification. */
4287 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4288 buffer = Qnil;
4289 else
4291 buffer = ps->buffer;
4292 if (!NILP (buffer))
4293 buffer = Fbuffer_name (buffer);
4294 else
4295 buffer = ps->name;
4296 if (!NILP (buffer))
4298 buffer = concat2 (buffer, caller);
4299 buffer = Fget_buffer_create (buffer);
4303 /* Generate a unique name for the new server process. Combine the
4304 server process name with the caller identification. */
4306 name = concat2 (ps->name, caller);
4307 proc = make_process (name);
4309 chan_process[s] = proc;
4311 #ifdef O_NONBLOCK
4312 fcntl (s, F_SETFL, O_NONBLOCK);
4313 #else
4314 #ifdef O_NDELAY
4315 fcntl (s, F_SETFL, O_NDELAY);
4316 #endif
4317 #endif
4319 p = XPROCESS (proc);
4321 /* Build new contact information for this setup. */
4322 contact = Fcopy_sequence (ps->childp);
4323 contact = Fplist_put (contact, QCserver, Qnil);
4324 contact = Fplist_put (contact, QChost, host);
4325 if (!NILP (service))
4326 contact = Fplist_put (contact, QCservice, service);
4327 contact = Fplist_put (contact, QCremote,
4328 conv_sockaddr_to_lisp (&saddr.sa, len));
4329 #ifdef HAVE_GETSOCKNAME
4330 len = sizeof saddr;
4331 if (getsockname (s, &saddr.sa, &len) == 0)
4332 contact = Fplist_put (contact, QClocal,
4333 conv_sockaddr_to_lisp (&saddr.sa, len));
4334 #endif
4336 p->childp = contact;
4337 p->plist = Fcopy_sequence (ps->plist);
4338 p->type = Qnetwork;
4340 p->buffer = buffer;
4341 p->sentinel = ps->sentinel;
4342 p->filter = ps->filter;
4343 p->command = Qnil;
4344 p->pid = 0;
4345 p->infd = s;
4346 p->outfd = s;
4347 p->status = Qrun;
4349 /* Client processes for accepted connections are not stopped initially. */
4350 if (!EQ (p->filter, Qt))
4352 FD_SET (s, &input_wait_mask);
4353 FD_SET (s, &non_keyboard_wait_mask);
4356 if (s > max_process_desc)
4357 max_process_desc = s;
4359 /* Setup coding system for new process based on server process.
4360 This seems to be the proper thing to do, as the coding system
4361 of the new process should reflect the settings at the time the
4362 server socket was opened; not the current settings. */
4364 p->decode_coding_system = ps->decode_coding_system;
4365 p->encode_coding_system = ps->encode_coding_system;
4366 setup_process_coding_systems (proc);
4368 p->decoding_buf = make_uninit_string (0);
4369 p->decoding_carryover = 0;
4370 p->encoding_buf = make_uninit_string (0);
4372 p->inherit_coding_system_flag
4373 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4375 if (!NILP (ps->log))
4376 call3 (ps->log, server, proc,
4377 concat3 (build_string ("accept from "),
4378 (STRINGP (host) ? host : build_string ("-")),
4379 build_string ("\n")));
4381 if (!NILP (p->sentinel))
4382 exec_sentinel (proc,
4383 concat3 (build_string ("open from "),
4384 (STRINGP (host) ? host : build_string ("-")),
4385 build_string ("\n")));
4388 /* This variable is different from waiting_for_input in keyboard.c.
4389 It is used to communicate to a lisp process-filter/sentinel (via the
4390 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4391 for user-input when that process-filter was called.
4392 waiting_for_input cannot be used as that is by definition 0 when
4393 lisp code is being evalled.
4394 This is also used in record_asynch_buffer_change.
4395 For that purpose, this must be 0
4396 when not inside wait_reading_process_output. */
4397 static int waiting_for_user_input_p;
4399 static Lisp_Object
4400 wait_reading_process_output_unwind (Lisp_Object data)
4402 waiting_for_user_input_p = XINT (data);
4403 return Qnil;
4406 /* This is here so breakpoints can be put on it. */
4407 static void
4408 wait_reading_process_output_1 (void)
4412 /* Use a wrapper around select to work around a bug in gdb 5.3.
4413 Normally, the wrapper is optimized away by inlining.
4415 If emacs is stopped inside select, the gdb backtrace doesn't
4416 show the function which called select, so it is practically
4417 impossible to step through wait_reading_process_output. */
4419 #ifndef select
4420 static INLINE int
4421 select_wrapper (int n, fd_set *rfd, fd_set *wfd, fd_set *xfd, struct timeval *tmo)
4423 return select (n, rfd, wfd, xfd, tmo);
4425 #define select select_wrapper
4426 #endif
4428 /* Read and dispose of subprocess output while waiting for timeout to
4429 elapse and/or keyboard input to be available.
4431 TIME_LIMIT is:
4432 timeout in seconds, or
4433 zero for no limit, or
4434 -1 means gobble data immediately available but don't wait for any.
4436 MICROSECS is:
4437 an additional duration to wait, measured in microseconds.
4438 If this is nonzero and time_limit is 0, then the timeout
4439 consists of MICROSECS only.
4441 READ_KBD is a lisp value:
4442 0 to ignore keyboard input, or
4443 1 to return when input is available, or
4444 -1 meaning caller will actually read the input, so don't throw to
4445 the quit handler, or
4447 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4448 output that arrives.
4450 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4451 (and gobble terminal input into the buffer if any arrives).
4453 If WAIT_PROC is specified, wait until something arrives from that
4454 process. The return value is true if we read some input from
4455 that process.
4457 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4458 (suspending output from other processes). A negative value
4459 means don't run any timers either.
4461 If WAIT_PROC is specified, then the function returns true if we
4462 received input from that process before the timeout elapsed.
4463 Otherwise, return true if we received input from any process. */
4466 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
4467 int do_display,
4468 Lisp_Object wait_for_cell,
4469 struct Lisp_Process *wait_proc, int just_wait_proc)
4471 register int channel, nfds;
4472 SELECT_TYPE Available;
4473 SELECT_TYPE Writeok;
4474 int check_write;
4475 int check_delay, no_avail;
4476 int xerrno;
4477 Lisp_Object proc;
4478 EMACS_TIME timeout, end_time;
4479 int wait_channel = -1;
4480 int got_some_input = 0;
4481 int count = SPECPDL_INDEX ();
4483 FD_ZERO (&Available);
4484 FD_ZERO (&Writeok);
4486 if (time_limit == 0 && microsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4487 && !(CONSP (wait_proc->status) && EQ (XCAR (wait_proc->status), Qexit)))
4488 message ("Blocking call to accept-process-output with quit inhibited!!");
4490 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4491 if (wait_proc != NULL)
4492 wait_channel = wait_proc->infd;
4494 record_unwind_protect (wait_reading_process_output_unwind,
4495 make_number (waiting_for_user_input_p));
4496 waiting_for_user_input_p = read_kbd;
4498 /* Since we may need to wait several times,
4499 compute the absolute time to return at. */
4500 if (time_limit || microsecs)
4502 EMACS_GET_TIME (end_time);
4503 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4504 EMACS_ADD_TIME (end_time, end_time, timeout);
4507 while (1)
4509 int timeout_reduced_for_timers = 0;
4511 /* If calling from keyboard input, do not quit
4512 since we want to return C-g as an input character.
4513 Otherwise, do pending quit if requested. */
4514 if (read_kbd >= 0)
4515 QUIT;
4516 #ifdef SYNC_INPUT
4517 else
4518 process_pending_signals ();
4519 #endif
4521 /* Exit now if the cell we're waiting for became non-nil. */
4522 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4523 break;
4525 /* Compute time from now till when time limit is up */
4526 /* Exit if already run out */
4527 if (time_limit == -1)
4529 /* -1 specified for timeout means
4530 gobble output available now
4531 but don't wait at all. */
4533 EMACS_SET_SECS_USECS (timeout, 0, 0);
4535 else if (time_limit || microsecs)
4537 EMACS_GET_TIME (timeout);
4538 EMACS_SUB_TIME (timeout, end_time, timeout);
4539 if (EMACS_TIME_NEG_P (timeout))
4540 break;
4542 else
4544 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4547 /* Normally we run timers here.
4548 But not if wait_for_cell; in those cases,
4549 the wait is supposed to be short,
4550 and those callers cannot handle running arbitrary Lisp code here. */
4551 if (NILP (wait_for_cell)
4552 && just_wait_proc >= 0)
4554 EMACS_TIME timer_delay;
4558 int old_timers_run = timers_run;
4559 struct buffer *old_buffer = current_buffer;
4560 Lisp_Object old_window = selected_window;
4562 timer_delay = timer_check (1);
4564 /* If a timer has run, this might have changed buffers
4565 an alike. Make read_key_sequence aware of that. */
4566 if (timers_run != old_timers_run
4567 && (old_buffer != current_buffer
4568 || !EQ (old_window, selected_window))
4569 && waiting_for_user_input_p == -1)
4570 record_asynch_buffer_change ();
4572 if (timers_run != old_timers_run && do_display)
4573 /* We must retry, since a timer may have requeued itself
4574 and that could alter the time_delay. */
4575 redisplay_preserve_echo_area (9);
4576 else
4577 break;
4579 while (!detect_input_pending ());
4581 /* If there is unread keyboard input, also return. */
4582 if (read_kbd != 0
4583 && requeued_events_pending_p ())
4584 break;
4586 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4588 EMACS_TIME difference;
4589 EMACS_SUB_TIME (difference, timer_delay, timeout);
4590 if (EMACS_TIME_NEG_P (difference))
4592 timeout = timer_delay;
4593 timeout_reduced_for_timers = 1;
4596 /* If time_limit is -1, we are not going to wait at all. */
4597 else if (time_limit != -1)
4599 /* This is so a breakpoint can be put here. */
4600 wait_reading_process_output_1 ();
4604 /* Cause C-g and alarm signals to take immediate action,
4605 and cause input available signals to zero out timeout.
4607 It is important that we do this before checking for process
4608 activity. If we get a SIGCHLD after the explicit checks for
4609 process activity, timeout is the only way we will know. */
4610 if (read_kbd < 0)
4611 set_waiting_for_input (&timeout);
4613 /* If status of something has changed, and no input is
4614 available, notify the user of the change right away. After
4615 this explicit check, we'll let the SIGCHLD handler zap
4616 timeout to get our attention. */
4617 if (update_tick != process_tick)
4619 SELECT_TYPE Atemp;
4620 SELECT_TYPE Ctemp;
4622 if (kbd_on_hold_p ())
4623 FD_ZERO (&Atemp);
4624 else
4625 Atemp = input_wait_mask;
4626 Ctemp = write_mask;
4628 EMACS_SET_SECS_USECS (timeout, 0, 0);
4629 if ((select (max (max_process_desc, max_input_desc) + 1,
4630 &Atemp,
4631 #ifdef NON_BLOCKING_CONNECT
4632 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4633 #else
4634 (SELECT_TYPE *)0,
4635 #endif
4636 (SELECT_TYPE *)0, &timeout)
4637 <= 0))
4639 /* It's okay for us to do this and then continue with
4640 the loop, since timeout has already been zeroed out. */
4641 clear_waiting_for_input ();
4642 status_notify (NULL);
4643 if (do_display) redisplay_preserve_echo_area (13);
4647 /* Don't wait for output from a non-running process. Just
4648 read whatever data has already been received. */
4649 if (wait_proc && wait_proc->raw_status_new)
4650 update_status (wait_proc);
4651 if (wait_proc
4652 && ! EQ (wait_proc->status, Qrun)
4653 && ! EQ (wait_proc->status, Qconnect))
4655 int nread, total_nread = 0;
4657 clear_waiting_for_input ();
4658 XSETPROCESS (proc, wait_proc);
4660 /* Read data from the process, until we exhaust it. */
4661 while (wait_proc->infd >= 0)
4663 nread = read_process_output (proc, wait_proc->infd);
4665 if (nread == 0)
4666 break;
4668 if (0 < nread)
4670 total_nread += nread;
4671 got_some_input = 1;
4673 #ifdef EIO
4674 else if (nread == -1 && EIO == errno)
4675 break;
4676 #endif
4677 #ifdef EAGAIN
4678 else if (nread == -1 && EAGAIN == errno)
4679 break;
4680 #endif
4681 #ifdef EWOULDBLOCK
4682 else if (nread == -1 && EWOULDBLOCK == errno)
4683 break;
4684 #endif
4686 if (total_nread > 0 && do_display)
4687 redisplay_preserve_echo_area (10);
4689 break;
4692 /* Wait till there is something to do */
4694 if (wait_proc && just_wait_proc)
4696 if (wait_proc->infd < 0) /* Terminated */
4697 break;
4698 FD_SET (wait_proc->infd, &Available);
4699 check_delay = 0;
4700 check_write = 0;
4702 else if (!NILP (wait_for_cell))
4704 Available = non_process_wait_mask;
4705 check_delay = 0;
4706 check_write = 0;
4708 else
4710 if (! read_kbd)
4711 Available = non_keyboard_wait_mask;
4712 else
4713 Available = input_wait_mask;
4714 Writeok = write_mask;
4715 #ifdef SELECT_CANT_DO_WRITE_MASK
4716 check_write = 0;
4717 #else
4718 check_write = 1;
4719 #endif
4720 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4723 /* If frame size has changed or the window is newly mapped,
4724 redisplay now, before we start to wait. There is a race
4725 condition here; if a SIGIO arrives between now and the select
4726 and indicates that a frame is trashed, the select may block
4727 displaying a trashed screen. */
4728 if (frame_garbaged && do_display)
4730 clear_waiting_for_input ();
4731 redisplay_preserve_echo_area (11);
4732 if (read_kbd < 0)
4733 set_waiting_for_input (&timeout);
4736 no_avail = 0;
4737 if (read_kbd && detect_input_pending ())
4739 nfds = 0;
4740 no_avail = 1;
4742 else
4745 #ifdef ADAPTIVE_READ_BUFFERING
4746 /* Set the timeout for adaptive read buffering if any
4747 process has non-zero read_output_skip and non-zero
4748 read_output_delay, and we are not reading output for a
4749 specific wait_channel. It is not executed if
4750 Vprocess_adaptive_read_buffering is nil. */
4751 if (process_output_skip && check_delay > 0)
4753 int usecs = EMACS_USECS (timeout);
4754 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4755 usecs = READ_OUTPUT_DELAY_MAX;
4756 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4758 proc = chan_process[channel];
4759 if (NILP (proc))
4760 continue;
4761 /* Find minimum non-zero read_output_delay among the
4762 processes with non-zero read_output_skip. */
4763 if (XPROCESS (proc)->read_output_delay > 0)
4765 check_delay--;
4766 if (!XPROCESS (proc)->read_output_skip)
4767 continue;
4768 FD_CLR (channel, &Available);
4769 XPROCESS (proc)->read_output_skip = 0;
4770 if (XPROCESS (proc)->read_output_delay < usecs)
4771 usecs = XPROCESS (proc)->read_output_delay;
4774 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4775 process_output_skip = 0;
4777 #endif
4778 #if defined (USE_GTK) || defined (HAVE_GCONF)
4779 nfds = xg_select
4780 #elif defined (HAVE_NS)
4781 nfds = ns_select
4782 #else
4783 nfds = select
4784 #endif
4785 (max (max_process_desc, max_input_desc) + 1,
4786 &Available,
4787 (check_write ? &Writeok : (SELECT_TYPE *)0),
4788 (SELECT_TYPE *)0, &timeout);
4791 xerrno = errno;
4793 /* Make C-g and alarm signals set flags again */
4794 clear_waiting_for_input ();
4796 /* If we woke up due to SIGWINCH, actually change size now. */
4797 do_pending_window_change (0);
4799 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4800 /* We wanted the full specified time, so return now. */
4801 break;
4802 if (nfds < 0)
4804 if (xerrno == EINTR)
4805 no_avail = 1;
4806 else if (xerrno == EBADF)
4808 #ifdef AIX
4809 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4810 the child's closure of the pts gives the parent a SIGHUP, and
4811 the ptc file descriptor is automatically closed,
4812 yielding EBADF here or at select() call above.
4813 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4814 in m/ibmrt-aix.h), and here we just ignore the select error.
4815 Cleanup occurs c/o status_notify after SIGCLD. */
4816 no_avail = 1; /* Cannot depend on values returned */
4817 #else
4818 abort ();
4819 #endif
4821 else
4822 error ("select error: %s", emacs_strerror (xerrno));
4825 if (no_avail)
4827 FD_ZERO (&Available);
4828 check_write = 0;
4831 #if 0 /* When polling is used, interrupt_input is 0,
4832 so get_input_pending should read the input.
4833 So this should not be needed. */
4834 /* If we are using polling for input,
4835 and we see input available, make it get read now.
4836 Otherwise it might not actually get read for a second.
4837 And on hpux, since we turn off polling in wait_reading_process_output,
4838 it might never get read at all if we don't spend much time
4839 outside of wait_reading_process_output. */
4840 if (read_kbd && interrupt_input
4841 && keyboard_bit_set (&Available)
4842 && input_polling_used ())
4843 kill (getpid (), SIGALRM);
4844 #endif
4846 /* Check for keyboard input */
4847 /* If there is any, return immediately
4848 to give it higher priority than subprocesses */
4850 if (read_kbd != 0)
4852 int old_timers_run = timers_run;
4853 struct buffer *old_buffer = current_buffer;
4854 Lisp_Object old_window = selected_window;
4855 int leave = 0;
4857 if (detect_input_pending_run_timers (do_display))
4859 swallow_events (do_display);
4860 if (detect_input_pending_run_timers (do_display))
4861 leave = 1;
4864 /* If a timer has run, this might have changed buffers
4865 an alike. Make read_key_sequence aware of that. */
4866 if (timers_run != old_timers_run
4867 && waiting_for_user_input_p == -1
4868 && (old_buffer != current_buffer
4869 || !EQ (old_window, selected_window)))
4870 record_asynch_buffer_change ();
4872 if (leave)
4873 break;
4876 /* If there is unread keyboard input, also return. */
4877 if (read_kbd != 0
4878 && requeued_events_pending_p ())
4879 break;
4881 /* If we are not checking for keyboard input now,
4882 do process events (but don't run any timers).
4883 This is so that X events will be processed.
4884 Otherwise they may have to wait until polling takes place.
4885 That would causes delays in pasting selections, for example.
4887 (We used to do this only if wait_for_cell.) */
4888 if (read_kbd == 0 && detect_input_pending ())
4890 swallow_events (do_display);
4891 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4892 if (detect_input_pending ())
4893 break;
4894 #endif
4897 /* Exit now if the cell we're waiting for became non-nil. */
4898 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4899 break;
4901 #ifdef SIGIO
4902 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4903 go read it. This can happen with X on BSD after logging out.
4904 In that case, there really is no input and no SIGIO,
4905 but select says there is input. */
4907 if (read_kbd && interrupt_input
4908 && keyboard_bit_set (&Available) && ! noninteractive)
4909 kill (getpid (), SIGIO);
4910 #endif
4912 if (! wait_proc)
4913 got_some_input |= nfds > 0;
4915 /* If checking input just got us a size-change event from X,
4916 obey it now if we should. */
4917 if (read_kbd || ! NILP (wait_for_cell))
4918 do_pending_window_change (0);
4920 /* Check for data from a process. */
4921 if (no_avail || nfds == 0)
4922 continue;
4924 for (channel = 0; channel <= max_input_desc; ++channel)
4926 struct fd_callback_data *d = &fd_callback_info[channel];
4927 if (FD_ISSET (channel, &Available)
4928 && d->func != 0
4929 && (d->condition & FOR_READ) != 0)
4930 d->func (channel, d->data, 1);
4931 if (FD_ISSET (channel, &write_mask)
4932 && d->func != 0
4933 && (d->condition & FOR_WRITE) != 0)
4934 d->func (channel, d->data, 0);
4937 /* Really FIRST_PROC_DESC should be 0 on Unix,
4938 but this is safer in the short run. */
4939 for (channel = 0; channel <= max_process_desc; channel++)
4941 if (FD_ISSET (channel, &Available)
4942 && FD_ISSET (channel, &non_keyboard_wait_mask)
4943 && !FD_ISSET (channel, &non_process_wait_mask))
4945 int nread;
4947 /* If waiting for this channel, arrange to return as
4948 soon as no more input to be processed. No more
4949 waiting. */
4950 if (wait_channel == channel)
4952 wait_channel = -1;
4953 time_limit = -1;
4954 got_some_input = 1;
4956 proc = chan_process[channel];
4957 if (NILP (proc))
4958 continue;
4960 /* If this is a server stream socket, accept connection. */
4961 if (EQ (XPROCESS (proc)->status, Qlisten))
4963 server_accept_connection (proc, channel);
4964 continue;
4967 /* Read data from the process, starting with our
4968 buffered-ahead character if we have one. */
4970 nread = read_process_output (proc, channel);
4971 if (nread > 0)
4973 /* Since read_process_output can run a filter,
4974 which can call accept-process-output,
4975 don't try to read from any other processes
4976 before doing the select again. */
4977 FD_ZERO (&Available);
4979 if (do_display)
4980 redisplay_preserve_echo_area (12);
4982 #ifdef EWOULDBLOCK
4983 else if (nread == -1 && errno == EWOULDBLOCK)
4985 #endif
4986 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4987 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4988 #ifdef O_NONBLOCK
4989 else if (nread == -1 && errno == EAGAIN)
4991 #else
4992 #ifdef O_NDELAY
4993 else if (nread == -1 && errno == EAGAIN)
4995 /* Note that we cannot distinguish between no input
4996 available now and a closed pipe.
4997 With luck, a closed pipe will be accompanied by
4998 subprocess termination and SIGCHLD. */
4999 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5001 #endif /* O_NDELAY */
5002 #endif /* O_NONBLOCK */
5003 #ifdef HAVE_PTYS
5004 /* On some OSs with ptys, when the process on one end of
5005 a pty exits, the other end gets an error reading with
5006 errno = EIO instead of getting an EOF (0 bytes read).
5007 Therefore, if we get an error reading and errno =
5008 EIO, just continue, because the child process has
5009 exited and should clean itself up soon (e.g. when we
5010 get a SIGCHLD).
5012 However, it has been known to happen that the SIGCHLD
5013 got lost. So raise the signal again just in case.
5014 It can't hurt. */
5015 else if (nread == -1 && errno == EIO)
5017 /* Clear the descriptor now, so we only raise the
5018 signal once. Don't do this if `process' is only
5019 a pty. */
5020 if (XPROCESS (proc)->pid != -2)
5022 FD_CLR (channel, &input_wait_mask);
5023 FD_CLR (channel, &non_keyboard_wait_mask);
5025 kill (getpid (), SIGCHLD);
5028 #endif /* HAVE_PTYS */
5029 /* If we can detect process termination, don't consider the process
5030 gone just because its pipe is closed. */
5031 #ifdef SIGCHLD
5032 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5034 #endif
5035 else
5037 /* Preserve status of processes already terminated. */
5038 XPROCESS (proc)->tick = ++process_tick;
5039 deactivate_process (proc);
5040 if (XPROCESS (proc)->raw_status_new)
5041 update_status (XPROCESS (proc));
5042 if (EQ (XPROCESS (proc)->status, Qrun))
5043 XPROCESS (proc)->status
5044 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5047 #ifdef NON_BLOCKING_CONNECT
5048 if (FD_ISSET (channel, &Writeok)
5049 && FD_ISSET (channel, &connect_wait_mask))
5051 struct Lisp_Process *p;
5053 FD_CLR (channel, &connect_wait_mask);
5054 FD_CLR (channel, &write_mask);
5055 if (--num_pending_connects < 0)
5056 abort ();
5058 proc = chan_process[channel];
5059 if (NILP (proc))
5060 continue;
5062 p = XPROCESS (proc);
5064 #ifdef GNU_LINUX
5065 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5066 So only use it on systems where it is known to work. */
5068 int xlen = sizeof (xerrno);
5069 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5070 xerrno = errno;
5072 #else
5074 struct sockaddr pname;
5075 int pnamelen = sizeof (pname);
5077 /* If connection failed, getpeername will fail. */
5078 xerrno = 0;
5079 if (getpeername (channel, &pname, &pnamelen) < 0)
5081 /* Obtain connect failure code through error slippage. */
5082 char dummy;
5083 xerrno = errno;
5084 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
5085 xerrno = errno;
5088 #endif
5089 if (xerrno)
5091 p->tick = ++process_tick;
5092 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5093 deactivate_process (proc);
5095 else
5097 p->status = Qrun;
5098 /* Execute the sentinel here. If we had relied on
5099 status_notify to do it later, it will read input
5100 from the process before calling the sentinel. */
5101 exec_sentinel (proc, build_string ("open\n"));
5102 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5104 FD_SET (p->infd, &input_wait_mask);
5105 FD_SET (p->infd, &non_keyboard_wait_mask);
5109 #endif /* NON_BLOCKING_CONNECT */
5110 } /* end for each file descriptor */
5111 } /* end while exit conditions not met */
5113 unbind_to (count, Qnil);
5115 /* If calling from keyboard input, do not quit
5116 since we want to return C-g as an input character.
5117 Otherwise, do pending quit if requested. */
5118 if (read_kbd >= 0)
5120 /* Prevent input_pending from remaining set if we quit. */
5121 clear_input_pending ();
5122 QUIT;
5125 return got_some_input;
5128 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5130 static Lisp_Object
5131 read_process_output_call (Lisp_Object fun_and_args)
5133 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5136 static Lisp_Object
5137 read_process_output_error_handler (Lisp_Object error)
5139 cmd_error_internal (error, "error in process filter: ");
5140 Vinhibit_quit = Qt;
5141 update_echo_area ();
5142 Fsleep_for (make_number (2), Qnil);
5143 return Qt;
5146 /* Read pending output from the process channel,
5147 starting with our buffered-ahead character if we have one.
5148 Yield number of decoded characters read.
5150 This function reads at most 4096 characters.
5151 If you want to read all available subprocess output,
5152 you must call it repeatedly until it returns zero.
5154 The characters read are decoded according to PROC's coding-system
5155 for decoding. */
5157 static int
5158 read_process_output (Lisp_Object proc, register int channel)
5160 register int nbytes;
5161 char *chars;
5162 register Lisp_Object outstream;
5163 register struct Lisp_Process *p = XPROCESS (proc);
5164 register EMACS_INT opoint;
5165 struct coding_system *coding = proc_decode_coding_system[channel];
5166 int carryover = p->decoding_carryover;
5167 int readmax = 4096;
5168 int count = SPECPDL_INDEX ();
5169 Lisp_Object odeactivate;
5171 chars = (char *) alloca (carryover + readmax);
5172 if (carryover)
5173 /* See the comment above. */
5174 memcpy (chars, SDATA (p->decoding_buf), carryover);
5176 #ifdef DATAGRAM_SOCKETS
5177 /* We have a working select, so proc_buffered_char is always -1. */
5178 if (DATAGRAM_CHAN_P (channel))
5180 int len = datagram_address[channel].len;
5181 nbytes = recvfrom (channel, chars + carryover, readmax,
5182 0, datagram_address[channel].sa, &len);
5184 else
5185 #endif
5186 if (proc_buffered_char[channel] < 0)
5188 #ifdef HAVE_GNUTLS
5189 if (XPROCESS (proc)->gnutls_p)
5190 nbytes = emacs_gnutls_read (channel, XPROCESS (proc),
5191 chars + carryover, readmax);
5192 else
5193 #endif
5194 nbytes = emacs_read (channel, chars + carryover, readmax);
5195 #ifdef ADAPTIVE_READ_BUFFERING
5196 if (nbytes > 0 && p->adaptive_read_buffering)
5198 int delay = p->read_output_delay;
5199 if (nbytes < 256)
5201 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5203 if (delay == 0)
5204 process_output_delay_count++;
5205 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5208 else if (delay > 0 && (nbytes == readmax))
5210 delay -= READ_OUTPUT_DELAY_INCREMENT;
5211 if (delay == 0)
5212 process_output_delay_count--;
5214 p->read_output_delay = delay;
5215 if (delay)
5217 p->read_output_skip = 1;
5218 process_output_skip = 1;
5221 #endif
5223 else
5225 chars[carryover] = proc_buffered_char[channel];
5226 proc_buffered_char[channel] = -1;
5227 #ifdef HAVE_GNUTLS
5228 if (XPROCESS (proc)->gnutls_p)
5229 nbytes = emacs_gnutls_read (channel, XPROCESS (proc),
5230 chars + carryover + 1, readmax - 1);
5231 else
5232 #endif
5233 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5234 if (nbytes < 0)
5235 nbytes = 1;
5236 else
5237 nbytes = nbytes + 1;
5240 p->decoding_carryover = 0;
5242 /* At this point, NBYTES holds number of bytes just received
5243 (including the one in proc_buffered_char[channel]). */
5244 if (nbytes <= 0)
5246 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5247 return nbytes;
5248 coding->mode |= CODING_MODE_LAST_BLOCK;
5251 /* Now set NBYTES how many bytes we must decode. */
5252 nbytes += carryover;
5254 odeactivate = Vdeactivate_mark;
5255 /* There's no good reason to let process filters change the current
5256 buffer, and many callers of accept-process-output, sit-for, and
5257 friends don't expect current-buffer to be changed from under them. */
5258 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
5260 /* Read and dispose of the process output. */
5261 outstream = p->filter;
5262 if (!NILP (outstream))
5264 Lisp_Object obuffer, okeymap;
5265 Lisp_Object text;
5266 int outer_running_asynch_code = running_asynch_code;
5267 int waiting = waiting_for_user_input_p;
5269 /* No need to gcpro these, because all we do with them later
5270 is test them for EQness, and none of them should be a string. */
5271 XSETBUFFER (obuffer, current_buffer);
5272 okeymap = current_buffer->keymap;
5274 /* We inhibit quit here instead of just catching it so that
5275 hitting ^G when a filter happens to be running won't screw
5276 it up. */
5277 specbind (Qinhibit_quit, Qt);
5278 specbind (Qlast_nonmenu_event, Qt);
5280 /* In case we get recursively called,
5281 and we already saved the match data nonrecursively,
5282 save the same match data in safely recursive fashion. */
5283 if (outer_running_asynch_code)
5285 Lisp_Object tem;
5286 /* Don't clobber the CURRENT match data, either! */
5287 tem = Fmatch_data (Qnil, Qnil, Qnil);
5288 restore_search_regs ();
5289 record_unwind_save_match_data ();
5290 Fset_match_data (tem, Qt);
5293 /* For speed, if a search happens within this code,
5294 save the match data in a special nonrecursive fashion. */
5295 running_asynch_code = 1;
5297 decode_coding_c_string (coding, chars, nbytes, Qt);
5298 text = coding->dst_object;
5299 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5300 /* A new coding system might be found. */
5301 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5303 p->decode_coding_system = Vlast_coding_system_used;
5305 /* Don't call setup_coding_system for
5306 proc_decode_coding_system[channel] here. It is done in
5307 detect_coding called via decode_coding above. */
5309 /* If a coding system for encoding is not yet decided, we set
5310 it as the same as coding-system for decoding.
5312 But, before doing that we must check if
5313 proc_encode_coding_system[p->outfd] surely points to a
5314 valid memory because p->outfd will be changed once EOF is
5315 sent to the process. */
5316 if (NILP (p->encode_coding_system)
5317 && proc_encode_coding_system[p->outfd])
5319 p->encode_coding_system
5320 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5321 setup_coding_system (p->encode_coding_system,
5322 proc_encode_coding_system[p->outfd]);
5326 if (coding->carryover_bytes > 0)
5328 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5329 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5330 memcpy (SDATA (p->decoding_buf), coding->carryover,
5331 coding->carryover_bytes);
5332 p->decoding_carryover = coding->carryover_bytes;
5334 if (SBYTES (text) > 0)
5335 internal_condition_case_1 (read_process_output_call,
5336 Fcons (outstream,
5337 Fcons (proc, Fcons (text, Qnil))),
5338 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5339 read_process_output_error_handler);
5341 /* If we saved the match data nonrecursively, restore it now. */
5342 restore_search_regs ();
5343 running_asynch_code = outer_running_asynch_code;
5345 /* Restore waiting_for_user_input_p as it was
5346 when we were called, in case the filter clobbered it. */
5347 waiting_for_user_input_p = waiting;
5349 #if 0 /* Call record_asynch_buffer_change unconditionally,
5350 because we might have changed minor modes or other things
5351 that affect key bindings. */
5352 if (! EQ (Fcurrent_buffer (), obuffer)
5353 || ! EQ (current_buffer->keymap, okeymap))
5354 #endif
5355 /* But do it only if the caller is actually going to read events.
5356 Otherwise there's no need to make him wake up, and it could
5357 cause trouble (for example it would make sit_for return). */
5358 if (waiting_for_user_input_p == -1)
5359 record_asynch_buffer_change ();
5362 /* If no filter, write into buffer if it isn't dead. */
5363 else if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5365 Lisp_Object old_read_only;
5366 EMACS_INT old_begv, old_zv;
5367 EMACS_INT old_begv_byte, old_zv_byte;
5368 EMACS_INT before, before_byte;
5369 EMACS_INT opoint_byte;
5370 Lisp_Object text;
5371 struct buffer *b;
5373 Fset_buffer (p->buffer);
5374 opoint = PT;
5375 opoint_byte = PT_BYTE;
5376 old_read_only = current_buffer->read_only;
5377 old_begv = BEGV;
5378 old_zv = ZV;
5379 old_begv_byte = BEGV_BYTE;
5380 old_zv_byte = ZV_BYTE;
5382 current_buffer->read_only = Qnil;
5384 /* Insert new output into buffer
5385 at the current end-of-output marker,
5386 thus preserving logical ordering of input and output. */
5387 if (XMARKER (p->mark)->buffer)
5388 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5389 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5390 ZV_BYTE));
5391 else
5392 SET_PT_BOTH (ZV, ZV_BYTE);
5393 before = PT;
5394 before_byte = PT_BYTE;
5396 /* If the output marker is outside of the visible region, save
5397 the restriction and widen. */
5398 if (! (BEGV <= PT && PT <= ZV))
5399 Fwiden ();
5401 decode_coding_c_string (coding, chars, nbytes, Qt);
5402 text = coding->dst_object;
5403 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5404 /* A new coding system might be found. See the comment in the
5405 similar code in the previous `if' block. */
5406 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5408 p->decode_coding_system = Vlast_coding_system_used;
5409 if (NILP (p->encode_coding_system)
5410 && proc_encode_coding_system[p->outfd])
5412 p->encode_coding_system
5413 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5414 setup_coding_system (p->encode_coding_system,
5415 proc_encode_coding_system[p->outfd]);
5418 if (coding->carryover_bytes > 0)
5420 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5421 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5422 memcpy (SDATA (p->decoding_buf), coding->carryover,
5423 coding->carryover_bytes);
5424 p->decoding_carryover = coding->carryover_bytes;
5426 /* Adjust the multibyteness of TEXT to that of the buffer. */
5427 if (NILP (current_buffer->enable_multibyte_characters)
5428 != ! STRING_MULTIBYTE (text))
5429 text = (STRING_MULTIBYTE (text)
5430 ? Fstring_as_unibyte (text)
5431 : Fstring_to_multibyte (text));
5432 /* Insert before markers in case we are inserting where
5433 the buffer's mark is, and the user's next command is Meta-y. */
5434 insert_from_string_before_markers (text, 0, 0,
5435 SCHARS (text), SBYTES (text), 0);
5437 /* Make sure the process marker's position is valid when the
5438 process buffer is changed in the signal_after_change above.
5439 W3 is known to do that. */
5440 if (BUFFERP (p->buffer)
5441 && (b = XBUFFER (p->buffer), b != current_buffer))
5442 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5443 else
5444 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5446 update_mode_lines++;
5448 /* Make sure opoint and the old restrictions
5449 float ahead of any new text just as point would. */
5450 if (opoint >= before)
5452 opoint += PT - before;
5453 opoint_byte += PT_BYTE - before_byte;
5455 if (old_begv > before)
5457 old_begv += PT - before;
5458 old_begv_byte += PT_BYTE - before_byte;
5460 if (old_zv >= before)
5462 old_zv += PT - before;
5463 old_zv_byte += PT_BYTE - before_byte;
5466 /* If the restriction isn't what it should be, set it. */
5467 if (old_begv != BEGV || old_zv != ZV)
5468 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5471 current_buffer->read_only = old_read_only;
5472 SET_PT_BOTH (opoint, opoint_byte);
5474 /* Handling the process output should not deactivate the mark. */
5475 Vdeactivate_mark = odeactivate;
5477 unbind_to (count, Qnil);
5478 return nbytes;
5481 /* Sending data to subprocess */
5483 jmp_buf send_process_frame;
5484 Lisp_Object process_sent_to;
5486 SIGTYPE
5487 send_process_trap (int ignore)
5489 SIGNAL_THREAD_CHECK (SIGPIPE);
5490 sigunblock (sigmask (SIGPIPE));
5491 longjmp (send_process_frame, 1);
5494 /* Send some data to process PROC.
5495 BUF is the beginning of the data; LEN is the number of characters.
5496 OBJECT is the Lisp object that the data comes from. If OBJECT is
5497 nil or t, it means that the data comes from C string.
5499 If OBJECT is not nil, the data is encoded by PROC's coding-system
5500 for encoding before it is sent.
5502 This function can evaluate Lisp code and can garbage collect. */
5504 static void
5505 send_process (volatile Lisp_Object proc, const unsigned char *volatile buf,
5506 volatile EMACS_INT len, volatile Lisp_Object object)
5508 /* Use volatile to protect variables from being clobbered by longjmp. */
5509 struct Lisp_Process *p = XPROCESS (proc);
5510 EMACS_INT rv;
5511 struct coding_system *coding;
5512 struct gcpro gcpro1;
5513 SIGTYPE (*volatile old_sigpipe) (int);
5515 GCPRO1 (object);
5517 if (p->raw_status_new)
5518 update_status (p);
5519 if (! EQ (p->status, Qrun))
5520 error ("Process %s not running", SDATA (p->name));
5521 if (p->outfd < 0)
5522 error ("Output file descriptor of %s is closed", SDATA (p->name));
5524 coding = proc_encode_coding_system[p->outfd];
5525 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5527 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5528 || (BUFFERP (object)
5529 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5530 || EQ (object, Qt))
5532 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5533 /* The coding system for encoding was changed to raw-text
5534 because we sent a unibyte text previously. Now we are
5535 sending a multibyte text, thus we must encode it by the
5536 original coding system specified for the current process. */
5537 setup_coding_system (p->encode_coding_system, coding);
5538 coding->src_multibyte = 1;
5540 else
5542 /* For sending a unibyte text, character code conversion should
5543 not take place but EOL conversion should. So, setup raw-text
5544 or one of the subsidiary if we have not yet done it. */
5545 if (CODING_REQUIRE_ENCODING (coding))
5547 if (CODING_REQUIRE_FLUSHING (coding))
5549 /* But, before changing the coding, we must flush out data. */
5550 coding->mode |= CODING_MODE_LAST_BLOCK;
5551 send_process (proc, "", 0, Qt);
5552 coding->mode &= CODING_MODE_LAST_BLOCK;
5554 setup_coding_system (raw_text_coding_system
5555 (Vlast_coding_system_used),
5556 coding);
5557 coding->src_multibyte = 0;
5560 coding->dst_multibyte = 0;
5562 if (CODING_REQUIRE_ENCODING (coding))
5564 coding->dst_object = Qt;
5565 if (BUFFERP (object))
5567 EMACS_INT from_byte, from, to;
5568 EMACS_INT save_pt, save_pt_byte;
5569 struct buffer *cur = current_buffer;
5571 set_buffer_internal (XBUFFER (object));
5572 save_pt = PT, save_pt_byte = PT_BYTE;
5574 from_byte = PTR_BYTE_POS (buf);
5575 from = BYTE_TO_CHAR (from_byte);
5576 to = BYTE_TO_CHAR (from_byte + len);
5577 TEMP_SET_PT_BOTH (from, from_byte);
5578 encode_coding_object (coding, object, from, from_byte,
5579 to, from_byte + len, Qt);
5580 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5581 set_buffer_internal (cur);
5583 else if (STRINGP (object))
5585 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5586 SBYTES (object), Qt);
5588 else
5590 coding->dst_object = make_unibyte_string (buf, len);
5591 coding->produced = len;
5594 len = coding->produced;
5595 object = coding->dst_object;
5596 buf = SDATA (object);
5599 if (pty_max_bytes == 0)
5601 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5602 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5603 if (pty_max_bytes < 0)
5604 pty_max_bytes = 250;
5605 #else
5606 pty_max_bytes = 250;
5607 #endif
5608 /* Deduct one, to leave space for the eof. */
5609 pty_max_bytes--;
5612 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5613 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5614 when returning with longjmp despite being declared volatile. */
5615 if (!setjmp (send_process_frame))
5617 process_sent_to = proc;
5618 while (len > 0)
5620 EMACS_INT this = len;
5622 /* Send this batch, using one or more write calls. */
5623 while (this > 0)
5625 int outfd = p->outfd;
5626 old_sigpipe = (SIGTYPE (*) (int)) signal (SIGPIPE, send_process_trap);
5627 #ifdef DATAGRAM_SOCKETS
5628 if (DATAGRAM_CHAN_P (outfd))
5630 rv = sendto (outfd, (char *) buf, this,
5631 0, datagram_address[outfd].sa,
5632 datagram_address[outfd].len);
5633 if (rv < 0 && errno == EMSGSIZE)
5635 signal (SIGPIPE, old_sigpipe);
5636 report_file_error ("sending datagram",
5637 Fcons (proc, Qnil));
5640 else
5641 #endif
5643 #ifdef HAVE_GNUTLS
5644 if (XPROCESS (proc)->gnutls_p)
5645 rv = emacs_gnutls_write (outfd,
5646 XPROCESS (proc),
5647 (char *) buf, this);
5648 else
5649 #endif
5650 rv = emacs_write (outfd, (char *) buf, this);
5651 #ifdef ADAPTIVE_READ_BUFFERING
5652 if (p->read_output_delay > 0
5653 && p->adaptive_read_buffering == 1)
5655 p->read_output_delay = 0;
5656 process_output_delay_count--;
5657 p->read_output_skip = 0;
5659 #endif
5661 signal (SIGPIPE, old_sigpipe);
5663 if (rv < 0)
5665 if (0
5666 #ifdef EWOULDBLOCK
5667 || errno == EWOULDBLOCK
5668 #endif
5669 #ifdef EAGAIN
5670 || errno == EAGAIN
5671 #endif
5673 /* Buffer is full. Wait, accepting input;
5674 that may allow the program
5675 to finish doing output and read more. */
5677 int offset = 0;
5679 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5680 /* A gross hack to work around a bug in FreeBSD.
5681 In the following sequence, read(2) returns
5682 bogus data:
5684 write(2) 1022 bytes
5685 write(2) 954 bytes, get EAGAIN
5686 read(2) 1024 bytes in process_read_output
5687 read(2) 11 bytes in process_read_output
5689 That is, read(2) returns more bytes than have
5690 ever been written successfully. The 1033 bytes
5691 read are the 1022 bytes written successfully
5692 after processing (for example with CRs added if
5693 the terminal is set up that way which it is
5694 here). The same bytes will be seen again in a
5695 later read(2), without the CRs. */
5697 if (errno == EAGAIN)
5699 int flags = FWRITE;
5700 ioctl (p->outfd, TIOCFLUSH, &flags);
5702 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5704 /* Running filters might relocate buffers or strings.
5705 Arrange to relocate BUF. */
5706 if (BUFFERP (object))
5707 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5708 else if (STRINGP (object))
5709 offset = buf - SDATA (object);
5711 #ifdef EMACS_HAS_USECS
5712 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5713 #else
5714 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5715 #endif
5717 if (BUFFERP (object))
5718 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5719 else if (STRINGP (object))
5720 buf = offset + SDATA (object);
5722 rv = 0;
5724 else
5725 /* This is a real error. */
5726 report_file_error ("writing to process", Fcons (proc, Qnil));
5728 buf += rv;
5729 len -= rv;
5730 this -= rv;
5734 else
5736 signal (SIGPIPE, old_sigpipe);
5737 proc = process_sent_to;
5738 p = XPROCESS (proc);
5739 p->raw_status_new = 0;
5740 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5741 p->tick = ++process_tick;
5742 deactivate_process (proc);
5743 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5746 UNGCPRO;
5749 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5750 3, 3, 0,
5751 doc: /* Send current contents of region as input to PROCESS.
5752 PROCESS may be a process, a buffer, the name of a process or buffer, or
5753 nil, indicating the current buffer's process.
5754 Called from program, takes three arguments, PROCESS, START and END.
5755 If the region is more than 500 characters long,
5756 it is sent in several bunches. This may happen even for shorter regions.
5757 Output from processes can arrive in between bunches. */)
5758 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5760 Lisp_Object proc;
5761 EMACS_INT start1, end1;
5763 proc = get_process (process);
5764 validate_region (&start, &end);
5766 if (XINT (start) < GPT && XINT (end) > GPT)
5767 move_gap (XINT (start));
5769 start1 = CHAR_TO_BYTE (XINT (start));
5770 end1 = CHAR_TO_BYTE (XINT (end));
5771 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5772 Fcurrent_buffer ());
5774 return Qnil;
5777 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5778 2, 2, 0,
5779 doc: /* Send PROCESS the contents of STRING as input.
5780 PROCESS may be a process, a buffer, the name of a process or buffer, or
5781 nil, indicating the current buffer's process.
5782 If STRING is more than 500 characters long,
5783 it is sent in several bunches. This may happen even for shorter strings.
5784 Output from processes can arrive in between bunches. */)
5785 (Lisp_Object process, Lisp_Object string)
5787 Lisp_Object proc;
5788 CHECK_STRING (string);
5789 proc = get_process (process);
5790 send_process (proc, SDATA (string),
5791 SBYTES (string), string);
5792 return Qnil;
5795 /* Return the foreground process group for the tty/pty that
5796 the process P uses. */
5797 static int
5798 emacs_get_tty_pgrp (struct Lisp_Process *p)
5800 int gid = -1;
5802 #ifdef TIOCGPGRP
5803 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5805 int fd;
5806 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5807 master side. Try the slave side. */
5808 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5810 if (fd != -1)
5812 ioctl (fd, TIOCGPGRP, &gid);
5813 emacs_close (fd);
5816 #endif /* defined (TIOCGPGRP ) */
5818 return gid;
5821 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5822 Sprocess_running_child_p, 0, 1, 0,
5823 doc: /* Return t if PROCESS has given the terminal to a child.
5824 If the operating system does not make it possible to find out,
5825 return t unconditionally. */)
5826 (Lisp_Object process)
5828 /* Initialize in case ioctl doesn't exist or gives an error,
5829 in a way that will cause returning t. */
5830 int gid;
5831 Lisp_Object proc;
5832 struct Lisp_Process *p;
5834 proc = get_process (process);
5835 p = XPROCESS (proc);
5837 if (!EQ (p->type, Qreal))
5838 error ("Process %s is not a subprocess",
5839 SDATA (p->name));
5840 if (p->infd < 0)
5841 error ("Process %s is not active",
5842 SDATA (p->name));
5844 gid = emacs_get_tty_pgrp (p);
5846 if (gid == p->pid)
5847 return Qnil;
5848 return Qt;
5851 /* send a signal number SIGNO to PROCESS.
5852 If CURRENT_GROUP is t, that means send to the process group
5853 that currently owns the terminal being used to communicate with PROCESS.
5854 This is used for various commands in shell mode.
5855 If CURRENT_GROUP is lambda, that means send to the process group
5856 that currently owns the terminal, but only if it is NOT the shell itself.
5858 If NOMSG is zero, insert signal-announcements into process's buffers
5859 right away.
5861 If we can, we try to signal PROCESS by sending control characters
5862 down the pty. This allows us to signal inferiors who have changed
5863 their uid, for which killpg would return an EPERM error. */
5865 static void
5866 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5867 int nomsg)
5869 Lisp_Object proc;
5870 register struct Lisp_Process *p;
5871 int gid;
5872 int no_pgrp = 0;
5874 proc = get_process (process);
5875 p = XPROCESS (proc);
5877 if (!EQ (p->type, Qreal))
5878 error ("Process %s is not a subprocess",
5879 SDATA (p->name));
5880 if (p->infd < 0)
5881 error ("Process %s is not active",
5882 SDATA (p->name));
5884 if (!p->pty_flag)
5885 current_group = Qnil;
5887 /* If we are using pgrps, get a pgrp number and make it negative. */
5888 if (NILP (current_group))
5889 /* Send the signal to the shell's process group. */
5890 gid = p->pid;
5891 else
5893 #ifdef SIGNALS_VIA_CHARACTERS
5894 /* If possible, send signals to the entire pgrp
5895 by sending an input character to it. */
5897 struct termios t;
5898 cc_t *sig_char = NULL;
5900 tcgetattr (p->infd, &t);
5902 switch (signo)
5904 case SIGINT:
5905 sig_char = &t.c_cc[VINTR];
5906 break;
5908 case SIGQUIT:
5909 sig_char = &t.c_cc[VQUIT];
5910 break;
5912 case SIGTSTP:
5913 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5914 sig_char = &t.c_cc[VSWTCH];
5915 #else
5916 sig_char = &t.c_cc[VSUSP];
5917 #endif
5918 break;
5921 if (sig_char && *sig_char != CDISABLE)
5923 send_process (proc, sig_char, 1, Qnil);
5924 return;
5926 /* If we can't send the signal with a character,
5927 fall through and send it another way. */
5929 /* The code above may fall through if it can't
5930 handle the signal. */
5931 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5933 #ifdef TIOCGPGRP
5934 /* Get the current pgrp using the tty itself, if we have that.
5935 Otherwise, use the pty to get the pgrp.
5936 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5937 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5938 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5939 His patch indicates that if TIOCGPGRP returns an error, then
5940 we should just assume that p->pid is also the process group id. */
5942 gid = emacs_get_tty_pgrp (p);
5944 if (gid == -1)
5945 /* If we can't get the information, assume
5946 the shell owns the tty. */
5947 gid = p->pid;
5949 /* It is not clear whether anything really can set GID to -1.
5950 Perhaps on some system one of those ioctls can or could do so.
5951 Or perhaps this is vestigial. */
5952 if (gid == -1)
5953 no_pgrp = 1;
5954 #else /* ! defined (TIOCGPGRP ) */
5955 /* Can't select pgrps on this system, so we know that
5956 the child itself heads the pgrp. */
5957 gid = p->pid;
5958 #endif /* ! defined (TIOCGPGRP ) */
5960 /* If current_group is lambda, and the shell owns the terminal,
5961 don't send any signal. */
5962 if (EQ (current_group, Qlambda) && gid == p->pid)
5963 return;
5966 switch (signo)
5968 #ifdef SIGCONT
5969 case SIGCONT:
5970 p->raw_status_new = 0;
5971 p->status = Qrun;
5972 p->tick = ++process_tick;
5973 if (!nomsg)
5975 status_notify (NULL);
5976 redisplay_preserve_echo_area (13);
5978 break;
5979 #endif /* ! defined (SIGCONT) */
5980 case SIGINT:
5981 case SIGQUIT:
5982 case SIGKILL:
5983 flush_pending_output (p->infd);
5984 break;
5987 /* If we don't have process groups, send the signal to the immediate
5988 subprocess. That isn't really right, but it's better than any
5989 obvious alternative. */
5990 if (no_pgrp)
5992 kill (p->pid, signo);
5993 return;
5996 /* gid may be a pid, or minus a pgrp's number */
5997 #ifdef TIOCSIGSEND
5998 if (!NILP (current_group))
6000 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6001 EMACS_KILLPG (gid, signo);
6003 else
6005 gid = - p->pid;
6006 kill (gid, signo);
6008 #else /* ! defined (TIOCSIGSEND) */
6009 EMACS_KILLPG (gid, signo);
6010 #endif /* ! defined (TIOCSIGSEND) */
6013 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6014 doc: /* Interrupt process PROCESS.
6015 PROCESS may be a process, a buffer, or the name of a process or buffer.
6016 No arg or nil means current buffer's process.
6017 Second arg CURRENT-GROUP non-nil means send signal to
6018 the current process-group of the process's controlling terminal
6019 rather than to the process's own process group.
6020 If the process is a shell, this means interrupt current subjob
6021 rather than the shell.
6023 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6024 don't send the signal. */)
6025 (Lisp_Object process, Lisp_Object current_group)
6027 process_send_signal (process, SIGINT, current_group, 0);
6028 return process;
6031 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6032 doc: /* Kill process PROCESS. May be process or name of one.
6033 See function `interrupt-process' for more details on usage. */)
6034 (Lisp_Object process, Lisp_Object current_group)
6036 process_send_signal (process, SIGKILL, current_group, 0);
6037 return process;
6040 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6041 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6042 See function `interrupt-process' for more details on usage. */)
6043 (Lisp_Object process, Lisp_Object current_group)
6045 process_send_signal (process, SIGQUIT, current_group, 0);
6046 return process;
6049 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6050 doc: /* Stop process PROCESS. May be process or name of one.
6051 See function `interrupt-process' for more details on usage.
6052 If PROCESS is a network or serial process, inhibit handling of incoming
6053 traffic. */)
6054 (Lisp_Object process, Lisp_Object current_group)
6056 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6058 struct Lisp_Process *p;
6060 p = XPROCESS (process);
6061 if (NILP (p->command)
6062 && p->infd >= 0)
6064 FD_CLR (p->infd, &input_wait_mask);
6065 FD_CLR (p->infd, &non_keyboard_wait_mask);
6067 p->command = Qt;
6068 return process;
6070 #ifndef SIGTSTP
6071 error ("No SIGTSTP support");
6072 #else
6073 process_send_signal (process, SIGTSTP, current_group, 0);
6074 #endif
6075 return process;
6078 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6079 doc: /* Continue process PROCESS. May be process or name of one.
6080 See function `interrupt-process' for more details on usage.
6081 If PROCESS is a network or serial process, resume handling of incoming
6082 traffic. */)
6083 (Lisp_Object process, Lisp_Object current_group)
6085 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6087 struct Lisp_Process *p;
6089 p = XPROCESS (process);
6090 if (EQ (p->command, Qt)
6091 && p->infd >= 0
6092 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6094 FD_SET (p->infd, &input_wait_mask);
6095 FD_SET (p->infd, &non_keyboard_wait_mask);
6096 #ifdef WINDOWSNT
6097 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6098 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6099 #else /* not WINDOWSNT */
6100 tcflush (p->infd, TCIFLUSH);
6101 #endif /* not WINDOWSNT */
6103 p->command = Qnil;
6104 return process;
6106 #ifdef SIGCONT
6107 process_send_signal (process, SIGCONT, current_group, 0);
6108 #else
6109 error ("No SIGCONT support");
6110 #endif
6111 return process;
6114 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6115 2, 2, "sProcess (name or number): \nnSignal code: ",
6116 doc: /* Send PROCESS the signal with code SIGCODE.
6117 PROCESS may also be a number specifying the process id of the
6118 process to signal; in this case, the process need not be a child of
6119 this Emacs.
6120 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6121 (Lisp_Object process, Lisp_Object sigcode)
6123 pid_t pid;
6125 if (INTEGERP (process))
6127 pid = XINT (process);
6128 goto got_it;
6131 if (FLOATP (process))
6133 pid = (pid_t) XFLOAT_DATA (process);
6134 goto got_it;
6137 if (STRINGP (process))
6139 Lisp_Object tem;
6140 if (tem = Fget_process (process), NILP (tem))
6142 pid = XINT (Fstring_to_number (process, make_number (10)));
6143 if (pid > 0)
6144 goto got_it;
6146 process = tem;
6148 else
6149 process = get_process (process);
6151 if (NILP (process))
6152 return process;
6154 CHECK_PROCESS (process);
6155 pid = XPROCESS (process)->pid;
6156 if (pid <= 0)
6157 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6159 got_it:
6161 #define parse_signal(NAME, VALUE) \
6162 else if (!xstrcasecmp (name, NAME)) \
6163 XSETINT (sigcode, VALUE)
6165 if (INTEGERP (sigcode))
6167 else
6169 unsigned char *name;
6171 CHECK_SYMBOL (sigcode);
6172 name = SDATA (SYMBOL_NAME (sigcode));
6174 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
6175 name += 3;
6177 if (0)
6179 #ifdef SIGUSR1
6180 parse_signal ("usr1", SIGUSR1);
6181 #endif
6182 #ifdef SIGUSR2
6183 parse_signal ("usr2", SIGUSR2);
6184 #endif
6185 #ifdef SIGTERM
6186 parse_signal ("term", SIGTERM);
6187 #endif
6188 #ifdef SIGHUP
6189 parse_signal ("hup", SIGHUP);
6190 #endif
6191 #ifdef SIGINT
6192 parse_signal ("int", SIGINT);
6193 #endif
6194 #ifdef SIGQUIT
6195 parse_signal ("quit", SIGQUIT);
6196 #endif
6197 #ifdef SIGILL
6198 parse_signal ("ill", SIGILL);
6199 #endif
6200 #ifdef SIGABRT
6201 parse_signal ("abrt", SIGABRT);
6202 #endif
6203 #ifdef SIGEMT
6204 parse_signal ("emt", SIGEMT);
6205 #endif
6206 #ifdef SIGKILL
6207 parse_signal ("kill", SIGKILL);
6208 #endif
6209 #ifdef SIGFPE
6210 parse_signal ("fpe", SIGFPE);
6211 #endif
6212 #ifdef SIGBUS
6213 parse_signal ("bus", SIGBUS);
6214 #endif
6215 #ifdef SIGSEGV
6216 parse_signal ("segv", SIGSEGV);
6217 #endif
6218 #ifdef SIGSYS
6219 parse_signal ("sys", SIGSYS);
6220 #endif
6221 #ifdef SIGPIPE
6222 parse_signal ("pipe", SIGPIPE);
6223 #endif
6224 #ifdef SIGALRM
6225 parse_signal ("alrm", SIGALRM);
6226 #endif
6227 #ifdef SIGURG
6228 parse_signal ("urg", SIGURG);
6229 #endif
6230 #ifdef SIGSTOP
6231 parse_signal ("stop", SIGSTOP);
6232 #endif
6233 #ifdef SIGTSTP
6234 parse_signal ("tstp", SIGTSTP);
6235 #endif
6236 #ifdef SIGCONT
6237 parse_signal ("cont", SIGCONT);
6238 #endif
6239 #ifdef SIGCHLD
6240 parse_signal ("chld", SIGCHLD);
6241 #endif
6242 #ifdef SIGTTIN
6243 parse_signal ("ttin", SIGTTIN);
6244 #endif
6245 #ifdef SIGTTOU
6246 parse_signal ("ttou", SIGTTOU);
6247 #endif
6248 #ifdef SIGIO
6249 parse_signal ("io", SIGIO);
6250 #endif
6251 #ifdef SIGXCPU
6252 parse_signal ("xcpu", SIGXCPU);
6253 #endif
6254 #ifdef SIGXFSZ
6255 parse_signal ("xfsz", SIGXFSZ);
6256 #endif
6257 #ifdef SIGVTALRM
6258 parse_signal ("vtalrm", SIGVTALRM);
6259 #endif
6260 #ifdef SIGPROF
6261 parse_signal ("prof", SIGPROF);
6262 #endif
6263 #ifdef SIGWINCH
6264 parse_signal ("winch", SIGWINCH);
6265 #endif
6266 #ifdef SIGINFO
6267 parse_signal ("info", SIGINFO);
6268 #endif
6269 else
6270 error ("Undefined signal name %s", name);
6273 #undef parse_signal
6275 return make_number (kill (pid, XINT (sigcode)));
6278 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6279 doc: /* Make PROCESS see end-of-file in its input.
6280 EOF comes after any text already sent to it.
6281 PROCESS may be a process, a buffer, the name of a process or buffer, or
6282 nil, indicating the current buffer's process.
6283 If PROCESS is a network connection, or is a process communicating
6284 through a pipe (as opposed to a pty), then you cannot send any more
6285 text to PROCESS after you call this function.
6286 If PROCESS is a serial process, wait until all output written to the
6287 process has been transmitted to the serial port. */)
6288 (Lisp_Object process)
6290 Lisp_Object proc;
6291 struct coding_system *coding;
6293 if (DATAGRAM_CONN_P (process))
6294 return process;
6296 proc = get_process (process);
6297 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6299 /* Make sure the process is really alive. */
6300 if (XPROCESS (proc)->raw_status_new)
6301 update_status (XPROCESS (proc));
6302 if (! EQ (XPROCESS (proc)->status, Qrun))
6303 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6305 if (CODING_REQUIRE_FLUSHING (coding))
6307 coding->mode |= CODING_MODE_LAST_BLOCK;
6308 send_process (proc, "", 0, Qnil);
6311 if (XPROCESS (proc)->pty_flag)
6312 send_process (proc, "\004", 1, Qnil);
6313 else if (EQ (XPROCESS (proc)->type, Qserial))
6315 #ifndef WINDOWSNT
6316 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6317 error ("tcdrain() failed: %s", emacs_strerror (errno));
6318 #endif /* not WINDOWSNT */
6319 /* Do nothing on Windows because writes are blocking. */
6321 else
6323 int old_outfd, new_outfd;
6325 #ifdef HAVE_SHUTDOWN
6326 /* If this is a network connection, or socketpair is used
6327 for communication with the subprocess, call shutdown to cause EOF.
6328 (In some old system, shutdown to socketpair doesn't work.
6329 Then we just can't win.) */
6330 if (EQ (XPROCESS (proc)->type, Qnetwork)
6331 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6332 shutdown (XPROCESS (proc)->outfd, 1);
6333 /* In case of socketpair, outfd == infd, so don't close it. */
6334 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6335 emacs_close (XPROCESS (proc)->outfd);
6336 #else /* not HAVE_SHUTDOWN */
6337 emacs_close (XPROCESS (proc)->outfd);
6338 #endif /* not HAVE_SHUTDOWN */
6339 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6340 if (new_outfd < 0)
6341 abort ();
6342 old_outfd = XPROCESS (proc)->outfd;
6344 if (!proc_encode_coding_system[new_outfd])
6345 proc_encode_coding_system[new_outfd]
6346 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6347 memcpy (proc_encode_coding_system[new_outfd],
6348 proc_encode_coding_system[old_outfd],
6349 sizeof (struct coding_system));
6350 memset (proc_encode_coding_system[old_outfd], 0,
6351 sizeof (struct coding_system));
6353 XPROCESS (proc)->outfd = new_outfd;
6355 return process;
6358 /* On receipt of a signal that a child status has changed, loop asking
6359 about children with changed statuses until the system says there
6360 are no more.
6362 All we do is change the status; we do not run sentinels or print
6363 notifications. That is saved for the next time keyboard input is
6364 done, in order to avoid timing errors.
6366 ** WARNING: this can be called during garbage collection.
6367 Therefore, it must not be fooled by the presence of mark bits in
6368 Lisp objects.
6370 ** USG WARNING: Although it is not obvious from the documentation
6371 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6372 signal() before executing at least one wait(), otherwise the
6373 handler will be called again, resulting in an infinite loop. The
6374 relevant portion of the documentation reads "SIGCLD signals will be
6375 queued and the signal-catching function will be continually
6376 reentered until the queue is empty". Invoking signal() causes the
6377 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6378 Inc.
6380 ** Malloc WARNING: This should never call malloc either directly or
6381 indirectly; if it does, that is a bug */
6383 #ifdef SIGCHLD
6384 SIGTYPE
6385 sigchld_handler (int signo)
6387 int old_errno = errno;
6388 Lisp_Object proc;
6389 struct Lisp_Process *p;
6391 SIGNAL_THREAD_CHECK (signo);
6393 while (1)
6395 pid_t pid;
6396 int w;
6397 Lisp_Object tail;
6399 #ifdef WNOHANG
6400 #ifndef WUNTRACED
6401 #define WUNTRACED 0
6402 #endif /* no WUNTRACED */
6403 /* Keep trying to get a status until we get a definitive result. */
6406 errno = 0;
6407 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6409 while (pid < 0 && errno == EINTR);
6411 if (pid <= 0)
6413 /* PID == 0 means no processes found, PID == -1 means a real
6414 failure. We have done all our job, so return. */
6416 errno = old_errno;
6417 return;
6419 #else
6420 pid = wait (&w);
6421 #endif /* no WNOHANG */
6423 /* Find the process that signaled us, and record its status. */
6425 /* The process can have been deleted by Fdelete_process. */
6426 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6428 Lisp_Object xpid = XCAR (tail);
6429 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6430 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6432 XSETCAR (tail, Qnil);
6433 goto sigchld_end_of_loop;
6437 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6438 p = 0;
6439 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6441 proc = XCDR (XCAR (tail));
6442 p = XPROCESS (proc);
6443 if (EQ (p->type, Qreal) && p->pid == pid)
6444 break;
6445 p = 0;
6448 /* Look for an asynchronous process whose pid hasn't been filled
6449 in yet. */
6450 if (p == 0)
6451 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6453 proc = XCDR (XCAR (tail));
6454 p = XPROCESS (proc);
6455 if (p->pid == -1)
6456 break;
6457 p = 0;
6460 /* Change the status of the process that was found. */
6461 if (p != 0)
6463 int clear_desc_flag = 0;
6465 p->tick = ++process_tick;
6466 p->raw_status = w;
6467 p->raw_status_new = 1;
6469 /* If process has terminated, stop waiting for its output. */
6470 if ((WIFSIGNALED (w) || WIFEXITED (w))
6471 && p->infd >= 0)
6472 clear_desc_flag = 1;
6474 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6475 if (clear_desc_flag)
6477 FD_CLR (p->infd, &input_wait_mask);
6478 FD_CLR (p->infd, &non_keyboard_wait_mask);
6481 /* Tell wait_reading_process_output that it needs to wake up and
6482 look around. */
6483 if (input_available_clear_time)
6484 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6487 /* There was no asynchronous process found for that pid: we have
6488 a synchronous process. */
6489 else
6491 synch_process_alive = 0;
6493 /* Report the status of the synchronous process. */
6494 if (WIFEXITED (w))
6495 synch_process_retcode = WRETCODE (w);
6496 else if (WIFSIGNALED (w))
6497 synch_process_termsig = WTERMSIG (w);
6499 /* Tell wait_reading_process_output that it needs to wake up and
6500 look around. */
6501 if (input_available_clear_time)
6502 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6505 sigchld_end_of_loop:
6508 /* On some systems, we must return right away.
6509 If any more processes want to signal us, we will
6510 get another signal.
6511 Otherwise (on systems that have WNOHANG), loop around
6512 to use up all the processes that have something to tell us. */
6513 #if (defined WINDOWSNT \
6514 || (defined USG && !defined GNU_LINUX \
6515 && !(defined HPUX && defined WNOHANG)))
6516 errno = old_errno;
6517 return;
6518 #endif /* USG, but not HPUX with WNOHANG */
6521 #endif /* SIGCHLD */
6524 static Lisp_Object
6525 exec_sentinel_unwind (Lisp_Object data)
6527 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6528 return Qnil;
6531 static Lisp_Object
6532 exec_sentinel_error_handler (Lisp_Object error)
6534 cmd_error_internal (error, "error in process sentinel: ");
6535 Vinhibit_quit = Qt;
6536 update_echo_area ();
6537 Fsleep_for (make_number (2), Qnil);
6538 return Qt;
6541 static void
6542 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6544 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6545 register struct Lisp_Process *p = XPROCESS (proc);
6546 int count = SPECPDL_INDEX ();
6547 int outer_running_asynch_code = running_asynch_code;
6548 int waiting = waiting_for_user_input_p;
6550 if (inhibit_sentinels)
6551 return;
6553 /* No need to gcpro these, because all we do with them later
6554 is test them for EQness, and none of them should be a string. */
6555 odeactivate = Vdeactivate_mark;
6556 XSETBUFFER (obuffer, current_buffer);
6557 okeymap = current_buffer->keymap;
6559 /* There's no good reason to let sentinels change the current
6560 buffer, and many callers of accept-process-output, sit-for, and
6561 friends don't expect current-buffer to be changed from under them. */
6562 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
6564 sentinel = p->sentinel;
6565 if (NILP (sentinel))
6566 return;
6568 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6569 assure that it gets restored no matter how the sentinel exits. */
6570 p->sentinel = Qnil;
6571 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6572 /* Inhibit quit so that random quits don't screw up a running filter. */
6573 specbind (Qinhibit_quit, Qt);
6574 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6576 /* In case we get recursively called,
6577 and we already saved the match data nonrecursively,
6578 save the same match data in safely recursive fashion. */
6579 if (outer_running_asynch_code)
6581 Lisp_Object tem;
6582 tem = Fmatch_data (Qnil, Qnil, Qnil);
6583 restore_search_regs ();
6584 record_unwind_save_match_data ();
6585 Fset_match_data (tem, Qt);
6588 /* For speed, if a search happens within this code,
6589 save the match data in a special nonrecursive fashion. */
6590 running_asynch_code = 1;
6592 internal_condition_case_1 (read_process_output_call,
6593 Fcons (sentinel,
6594 Fcons (proc, Fcons (reason, Qnil))),
6595 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6596 exec_sentinel_error_handler);
6598 /* If we saved the match data nonrecursively, restore it now. */
6599 restore_search_regs ();
6600 running_asynch_code = outer_running_asynch_code;
6602 Vdeactivate_mark = odeactivate;
6604 /* Restore waiting_for_user_input_p as it was
6605 when we were called, in case the filter clobbered it. */
6606 waiting_for_user_input_p = waiting;
6608 #if 0
6609 if (! EQ (Fcurrent_buffer (), obuffer)
6610 || ! EQ (current_buffer->keymap, okeymap))
6611 #endif
6612 /* But do it only if the caller is actually going to read events.
6613 Otherwise there's no need to make him wake up, and it could
6614 cause trouble (for example it would make sit_for return). */
6615 if (waiting_for_user_input_p == -1)
6616 record_asynch_buffer_change ();
6618 unbind_to (count, Qnil);
6621 /* Report all recent events of a change in process status
6622 (either run the sentinel or output a message).
6623 This is usually done while Emacs is waiting for keyboard input
6624 but can be done at other times. */
6626 static void
6627 status_notify (struct Lisp_Process *deleting_process)
6629 register Lisp_Object proc, buffer;
6630 Lisp_Object tail, msg;
6631 struct gcpro gcpro1, gcpro2;
6633 tail = Qnil;
6634 msg = Qnil;
6635 /* We need to gcpro tail; if read_process_output calls a filter
6636 which deletes a process and removes the cons to which tail points
6637 from Vprocess_alist, and then causes a GC, tail is an unprotected
6638 reference. */
6639 GCPRO2 (tail, msg);
6641 /* Set this now, so that if new processes are created by sentinels
6642 that we run, we get called again to handle their status changes. */
6643 update_tick = process_tick;
6645 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6647 Lisp_Object symbol;
6648 register struct Lisp_Process *p;
6650 proc = Fcdr (XCAR (tail));
6651 p = XPROCESS (proc);
6653 if (p->tick != p->update_tick)
6655 p->update_tick = p->tick;
6657 /* If process is still active, read any output that remains. */
6658 while (! EQ (p->filter, Qt)
6659 && ! EQ (p->status, Qconnect)
6660 && ! EQ (p->status, Qlisten)
6661 /* Network or serial process not stopped: */
6662 && ! EQ (p->command, Qt)
6663 && p->infd >= 0
6664 && p != deleting_process
6665 && read_process_output (proc, p->infd) > 0);
6667 buffer = p->buffer;
6669 /* Get the text to use for the message. */
6670 if (p->raw_status_new)
6671 update_status (p);
6672 msg = status_message (p);
6674 /* If process is terminated, deactivate it or delete it. */
6675 symbol = p->status;
6676 if (CONSP (p->status))
6677 symbol = XCAR (p->status);
6679 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6680 || EQ (symbol, Qclosed))
6682 if (delete_exited_processes)
6683 remove_process (proc);
6684 else
6685 deactivate_process (proc);
6688 /* The actions above may have further incremented p->tick.
6689 So set p->update_tick again
6690 so that an error in the sentinel will not cause
6691 this code to be run again. */
6692 p->update_tick = p->tick;
6693 /* Now output the message suitably. */
6694 if (!NILP (p->sentinel))
6695 exec_sentinel (proc, msg);
6696 /* Don't bother with a message in the buffer
6697 when a process becomes runnable. */
6698 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6700 Lisp_Object tem;
6701 struct buffer *old = current_buffer;
6702 EMACS_INT opoint, opoint_byte;
6703 EMACS_INT before, before_byte;
6705 /* Avoid error if buffer is deleted
6706 (probably that's why the process is dead, too) */
6707 if (NILP (XBUFFER (buffer)->name))
6708 continue;
6709 Fset_buffer (buffer);
6711 opoint = PT;
6712 opoint_byte = PT_BYTE;
6713 /* Insert new output into buffer
6714 at the current end-of-output marker,
6715 thus preserving logical ordering of input and output. */
6716 if (XMARKER (p->mark)->buffer)
6717 Fgoto_char (p->mark);
6718 else
6719 SET_PT_BOTH (ZV, ZV_BYTE);
6721 before = PT;
6722 before_byte = PT_BYTE;
6724 tem = current_buffer->read_only;
6725 current_buffer->read_only = Qnil;
6726 insert_string ("\nProcess ");
6727 Finsert (1, &p->name);
6728 insert_string (" ");
6729 Finsert (1, &msg);
6730 current_buffer->read_only = tem;
6731 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6733 if (opoint >= before)
6734 SET_PT_BOTH (opoint + (PT - before),
6735 opoint_byte + (PT_BYTE - before_byte));
6736 else
6737 SET_PT_BOTH (opoint, opoint_byte);
6739 set_buffer_internal (old);
6742 } /* end for */
6744 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6745 UNGCPRO;
6749 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6750 Sset_process_coding_system, 1, 3, 0,
6751 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6752 DECODING will be used to decode subprocess output and ENCODING to
6753 encode subprocess input. */)
6754 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6756 register struct Lisp_Process *p;
6758 CHECK_PROCESS (process);
6759 p = XPROCESS (process);
6760 if (p->infd < 0)
6761 error ("Input file descriptor of %s closed", SDATA (p->name));
6762 if (p->outfd < 0)
6763 error ("Output file descriptor of %s closed", SDATA (p->name));
6764 Fcheck_coding_system (decoding);
6765 Fcheck_coding_system (encoding);
6766 encoding = coding_inherit_eol_type (encoding, Qnil);
6767 p->decode_coding_system = decoding;
6768 p->encode_coding_system = encoding;
6769 setup_process_coding_systems (process);
6771 return Qnil;
6774 DEFUN ("process-coding-system",
6775 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6776 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6777 (register Lisp_Object process)
6779 CHECK_PROCESS (process);
6780 return Fcons (XPROCESS (process)->decode_coding_system,
6781 XPROCESS (process)->encode_coding_system);
6784 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6785 Sset_process_filter_multibyte, 2, 2, 0,
6786 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6787 If FLAG is non-nil, the filter is given multibyte strings.
6788 If FLAG is nil, the filter is given unibyte strings. In this case,
6789 all character code conversion except for end-of-line conversion is
6790 suppressed. */)
6791 (Lisp_Object process, Lisp_Object flag)
6793 register struct Lisp_Process *p;
6795 CHECK_PROCESS (process);
6796 p = XPROCESS (process);
6797 if (NILP (flag))
6798 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6799 setup_process_coding_systems (process);
6801 return Qnil;
6804 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6805 Sprocess_filter_multibyte_p, 1, 1, 0,
6806 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6807 (Lisp_Object process)
6809 register struct Lisp_Process *p;
6810 struct coding_system *coding;
6812 CHECK_PROCESS (process);
6813 p = XPROCESS (process);
6814 coding = proc_decode_coding_system[p->infd];
6815 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6821 void
6822 add_gpm_wait_descriptor (int desc)
6824 add_keyboard_wait_descriptor (desc);
6827 void
6828 delete_gpm_wait_descriptor (int desc)
6830 delete_keyboard_wait_descriptor (desc);
6833 /* Return nonzero if *MASK has a bit set
6834 that corresponds to one of the keyboard input descriptors. */
6836 static int
6837 keyboard_bit_set (fd_set *mask)
6839 int fd;
6841 for (fd = 0; fd <= max_input_desc; fd++)
6842 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6843 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6844 return 1;
6846 return 0;
6849 #else /* not subprocesses */
6851 /* Defined on msdos.c. */
6852 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6853 EMACS_TIME *);
6855 /* Implementation of wait_reading_process_output, assuming that there
6856 are no subprocesses. Used only by the MS-DOS build.
6858 Wait for timeout to elapse and/or keyboard input to be available.
6860 time_limit is:
6861 timeout in seconds, or
6862 zero for no limit, or
6863 -1 means gobble data immediately available but don't wait for any.
6865 read_kbd is a Lisp_Object:
6866 0 to ignore keyboard input, or
6867 1 to return when input is available, or
6868 -1 means caller will actually read the input, so don't throw to
6869 the quit handler.
6871 see full version for other parameters. We know that wait_proc will
6872 always be NULL, since `subprocesses' isn't defined.
6874 do_display != 0 means redisplay should be done to show subprocess
6875 output that arrives.
6877 Return true if we received input from any process. */
6880 wait_reading_process_output (int time_limit, int microsecs, int read_kbd,
6881 int do_display,
6882 Lisp_Object wait_for_cell,
6883 struct Lisp_Process *wait_proc, int just_wait_proc)
6885 register int nfds;
6886 EMACS_TIME end_time, timeout;
6887 SELECT_TYPE waitchannels;
6888 int xerrno;
6890 /* What does time_limit really mean? */
6891 if (time_limit || microsecs)
6893 EMACS_GET_TIME (end_time);
6894 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6895 EMACS_ADD_TIME (end_time, end_time, timeout);
6898 /* Turn off periodic alarms (in case they are in use)
6899 and then turn off any other atimers,
6900 because the select emulator uses alarms. */
6901 stop_polling ();
6902 turn_on_atimers (0);
6904 while (1)
6906 int timeout_reduced_for_timers = 0;
6908 /* If calling from keyboard input, do not quit
6909 since we want to return C-g as an input character.
6910 Otherwise, do pending quit if requested. */
6911 if (read_kbd >= 0)
6912 QUIT;
6914 /* Exit now if the cell we're waiting for became non-nil. */
6915 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6916 break;
6918 /* Compute time from now till when time limit is up */
6919 /* Exit if already run out */
6920 if (time_limit == -1)
6922 /* -1 specified for timeout means
6923 gobble output available now
6924 but don't wait at all. */
6926 EMACS_SET_SECS_USECS (timeout, 0, 0);
6928 else if (time_limit || microsecs)
6930 EMACS_GET_TIME (timeout);
6931 EMACS_SUB_TIME (timeout, end_time, timeout);
6932 if (EMACS_TIME_NEG_P (timeout))
6933 break;
6935 else
6937 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6940 /* If our caller will not immediately handle keyboard events,
6941 run timer events directly.
6942 (Callers that will immediately read keyboard events
6943 call timer_delay on their own.) */
6944 if (NILP (wait_for_cell))
6946 EMACS_TIME timer_delay;
6950 int old_timers_run = timers_run;
6951 timer_delay = timer_check (1);
6952 if (timers_run != old_timers_run && do_display)
6953 /* We must retry, since a timer may have requeued itself
6954 and that could alter the time delay. */
6955 redisplay_preserve_echo_area (14);
6956 else
6957 break;
6959 while (!detect_input_pending ());
6961 /* If there is unread keyboard input, also return. */
6962 if (read_kbd != 0
6963 && requeued_events_pending_p ())
6964 break;
6966 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6968 EMACS_TIME difference;
6969 EMACS_SUB_TIME (difference, timer_delay, timeout);
6970 if (EMACS_TIME_NEG_P (difference))
6972 timeout = timer_delay;
6973 timeout_reduced_for_timers = 1;
6978 /* Cause C-g and alarm signals to take immediate action,
6979 and cause input available signals to zero out timeout. */
6980 if (read_kbd < 0)
6981 set_waiting_for_input (&timeout);
6983 /* Wait till there is something to do. */
6985 if (! read_kbd && NILP (wait_for_cell))
6986 FD_ZERO (&waitchannels);
6987 else
6988 FD_SET (0, &waitchannels);
6990 /* If a frame has been newly mapped and needs updating,
6991 reprocess its display stuff. */
6992 if (frame_garbaged && do_display)
6994 clear_waiting_for_input ();
6995 redisplay_preserve_echo_area (15);
6996 if (read_kbd < 0)
6997 set_waiting_for_input (&timeout);
7000 if (read_kbd && detect_input_pending ())
7002 nfds = 0;
7003 FD_ZERO (&waitchannels);
7005 else
7006 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7007 &timeout);
7009 xerrno = errno;
7011 /* Make C-g and alarm signals set flags again */
7012 clear_waiting_for_input ();
7014 /* If we woke up due to SIGWINCH, actually change size now. */
7015 do_pending_window_change (0);
7017 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7018 /* We waited the full specified time, so return now. */
7019 break;
7021 if (nfds == -1)
7023 /* If the system call was interrupted, then go around the
7024 loop again. */
7025 if (xerrno == EINTR)
7026 FD_ZERO (&waitchannels);
7027 else
7028 error ("select error: %s", emacs_strerror (xerrno));
7031 /* Check for keyboard input */
7033 if (read_kbd
7034 && detect_input_pending_run_timers (do_display))
7036 swallow_events (do_display);
7037 if (detect_input_pending_run_timers (do_display))
7038 break;
7041 /* If there is unread keyboard input, also return. */
7042 if (read_kbd
7043 && requeued_events_pending_p ())
7044 break;
7046 /* If wait_for_cell. check for keyboard input
7047 but don't run any timers.
7048 ??? (It seems wrong to me to check for keyboard
7049 input at all when wait_for_cell, but the code
7050 has been this way since July 1994.
7051 Try changing this after version 19.31.) */
7052 if (! NILP (wait_for_cell)
7053 && detect_input_pending ())
7055 swallow_events (do_display);
7056 if (detect_input_pending ())
7057 break;
7060 /* Exit now if the cell we're waiting for became non-nil. */
7061 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7062 break;
7065 start_polling ();
7067 return 0;
7070 #endif /* not subprocesses */
7072 /* The following functions are needed even if async subprocesses are
7073 not supported. Some of them are no-op stubs in that case. */
7075 /* Add DESC to the set of keyboard input descriptors. */
7077 void
7078 add_keyboard_wait_descriptor (int desc)
7080 #ifdef subprocesses /* actually means "not MSDOS" */
7081 FD_SET (desc, &input_wait_mask);
7082 FD_SET (desc, &non_process_wait_mask);
7083 if (desc > max_input_desc)
7084 max_input_desc = desc;
7085 #endif
7088 /* From now on, do not expect DESC to give keyboard input. */
7090 void
7091 delete_keyboard_wait_descriptor (int desc)
7093 #ifdef subprocesses
7094 int fd;
7095 int lim = max_input_desc;
7097 FD_CLR (desc, &input_wait_mask);
7098 FD_CLR (desc, &non_process_wait_mask);
7100 if (desc == max_input_desc)
7101 for (fd = 0; fd < lim; fd++)
7102 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
7103 max_input_desc = fd;
7104 #endif
7107 /* Setup coding systems of PROCESS. */
7109 void
7110 setup_process_coding_systems (Lisp_Object process)
7112 #ifdef subprocesses
7113 struct Lisp_Process *p = XPROCESS (process);
7114 int inch = p->infd;
7115 int outch = p->outfd;
7116 Lisp_Object coding_system;
7118 if (inch < 0 || outch < 0)
7119 return;
7121 if (!proc_decode_coding_system[inch])
7122 proc_decode_coding_system[inch]
7123 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7124 coding_system = p->decode_coding_system;
7125 if (! NILP (p->filter))
7127 else if (BUFFERP (p->buffer))
7129 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
7130 coding_system = raw_text_coding_system (coding_system);
7132 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
7134 if (!proc_encode_coding_system[outch])
7135 proc_encode_coding_system[outch]
7136 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
7137 setup_coding_system (p->encode_coding_system,
7138 proc_encode_coding_system[outch]);
7139 #endif
7142 /* Close all descriptors currently in use for communication
7143 with subprocess. This is used in a newly-forked subprocess
7144 to get rid of irrelevant descriptors. */
7146 void
7147 close_process_descs (void)
7149 #ifndef DOS_NT
7150 int i;
7151 for (i = 0; i < MAXDESC; i++)
7153 Lisp_Object process;
7154 process = chan_process[i];
7155 if (!NILP (process))
7157 int in = XPROCESS (process)->infd;
7158 int out = XPROCESS (process)->outfd;
7159 if (in >= 0)
7160 emacs_close (in);
7161 if (out >= 0 && in != out)
7162 emacs_close (out);
7165 #endif
7168 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7169 doc: /* Return the (or a) process associated with BUFFER.
7170 BUFFER may be a buffer or the name of one. */)
7171 (register Lisp_Object buffer)
7173 #ifdef subprocesses
7174 register Lisp_Object buf, tail, proc;
7176 if (NILP (buffer)) return Qnil;
7177 buf = Fget_buffer (buffer);
7178 if (NILP (buf)) return Qnil;
7180 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7182 proc = Fcdr (XCAR (tail));
7183 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
7184 return proc;
7186 #endif /* subprocesses */
7187 return Qnil;
7190 DEFUN ("process-inherit-coding-system-flag",
7191 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7192 1, 1, 0,
7193 doc: /* Return the value of inherit-coding-system flag for PROCESS.
7194 If this flag is t, `buffer-file-coding-system' of the buffer
7195 associated with PROCESS will inherit the coding system used to decode
7196 the process output. */)
7197 (register Lisp_Object process)
7199 #ifdef subprocesses
7200 CHECK_PROCESS (process);
7201 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
7202 #else
7203 /* Ignore the argument and return the value of
7204 inherit-process-coding-system. */
7205 return inherit_process_coding_system ? Qt : Qnil;
7206 #endif
7209 /* Kill all processes associated with `buffer'.
7210 If `buffer' is nil, kill all processes */
7212 void
7213 kill_buffer_processes (Lisp_Object buffer)
7215 #ifdef subprocesses
7216 Lisp_Object tail, proc;
7218 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7220 proc = XCDR (XCAR (tail));
7221 if (PROCESSP (proc)
7222 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
7224 if (NETCONN_P (proc) || SERIALCONN_P (proc))
7225 Fdelete_process (proc);
7226 else if (XPROCESS (proc)->infd >= 0)
7227 process_send_signal (proc, SIGHUP, Qnil, 1);
7230 #else /* subprocesses */
7231 /* Since we have no subprocesses, this does nothing. */
7232 #endif /* subprocesses */
7235 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
7236 0, 0, 0,
7237 doc: /* Returns non-nil if Emacs is waiting for input from the user.
7238 This is intended for use by asynchronous process output filters and sentinels. */)
7239 (void)
7241 #ifdef subprocesses
7242 return (waiting_for_user_input_p ? Qt : Qnil);
7243 #else
7244 return Qnil;
7245 #endif
7248 /* Stop reading input from keyboard sources. */
7250 void
7251 hold_keyboard_input (void)
7253 kbd_is_on_hold = 1;
7256 /* Resume reading input from keyboard sources. */
7258 void
7259 unhold_keyboard_input (void)
7261 kbd_is_on_hold = 0;
7264 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7267 kbd_on_hold_p (void)
7269 return kbd_is_on_hold;
7273 /* Enumeration of and access to system processes a-la ps(1). */
7275 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7276 0, 0, 0,
7277 doc: /* Return a list of numerical process IDs of all running processes.
7278 If this functionality is unsupported, return nil.
7280 See `process-attributes' for getting attributes of a process given its ID. */)
7281 (void)
7283 return list_system_processes ();
7286 DEFUN ("process-attributes", Fprocess_attributes,
7287 Sprocess_attributes, 1, 1, 0,
7288 doc: /* Return attributes of the process given by its PID, a number.
7290 Value is an alist where each element is a cons cell of the form
7292 \(KEY . VALUE)
7294 If this functionality is unsupported, the value is nil.
7296 See `list-system-processes' for getting a list of all process IDs.
7298 The KEYs of the attributes that this function may return are listed
7299 below, together with the type of the associated VALUE (in parentheses).
7300 Not all platforms support all of these attributes; unsupported
7301 attributes will not appear in the returned alist.
7302 Unless explicitly indicated otherwise, numbers can have either
7303 integer or floating point values.
7305 euid -- Effective user User ID of the process (number)
7306 user -- User name corresponding to euid (string)
7307 egid -- Effective user Group ID of the process (number)
7308 group -- Group name corresponding to egid (string)
7309 comm -- Command name (executable name only) (string)
7310 state -- Process state code, such as "S", "R", or "T" (string)
7311 ppid -- Parent process ID (number)
7312 pgrp -- Process group ID (number)
7313 sess -- Session ID, i.e. process ID of session leader (number)
7314 ttname -- Controlling tty name (string)
7315 tpgid -- ID of foreground process group on the process's tty (number)
7316 minflt -- number of minor page faults (number)
7317 majflt -- number of major page faults (number)
7318 cminflt -- cumulative number of minor page faults (number)
7319 cmajflt -- cumulative number of major page faults (number)
7320 utime -- user time used by the process, in the (HIGH LOW USEC) format
7321 stime -- system time used by the process, in the (HIGH LOW USEC) format
7322 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7323 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7324 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7325 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7326 pri -- priority of the process (number)
7327 nice -- nice value of the process (number)
7328 thcount -- process thread count (number)
7329 start -- time the process started, in the (HIGH LOW USEC) format
7330 vsize -- virtual memory size of the process in KB's (number)
7331 rss -- resident set size of the process in KB's (number)
7332 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7333 pcpu -- percents of CPU time used by the process (floating-point number)
7334 pmem -- percents of total physical memory used by process's resident set
7335 (floating-point number)
7336 args -- command line which invoked the process (string). */)
7337 ( Lisp_Object pid)
7339 return system_process_attributes (pid);
7343 void
7344 init_process (void)
7346 #ifdef subprocesses
7347 register int i;
7349 inhibit_sentinels = 0;
7351 #ifdef SIGCHLD
7352 #ifndef CANNOT_DUMP
7353 if (! noninteractive || initialized)
7354 #endif
7355 signal (SIGCHLD, sigchld_handler);
7356 #endif
7358 FD_ZERO (&input_wait_mask);
7359 FD_ZERO (&non_keyboard_wait_mask);
7360 FD_ZERO (&non_process_wait_mask);
7361 FD_ZERO (&write_mask);
7362 max_process_desc = 0;
7363 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7365 #ifdef NON_BLOCKING_CONNECT
7366 FD_ZERO (&connect_wait_mask);
7367 num_pending_connects = 0;
7368 #endif
7370 #ifdef ADAPTIVE_READ_BUFFERING
7371 process_output_delay_count = 0;
7372 process_output_skip = 0;
7373 #endif
7375 /* Don't do this, it caused infinite select loops. The display
7376 method should call add_keyboard_wait_descriptor on stdin if it
7377 needs that. */
7378 #if 0
7379 FD_SET (0, &input_wait_mask);
7380 #endif
7382 Vprocess_alist = Qnil;
7383 #ifdef SIGCHLD
7384 deleted_pid_list = Qnil;
7385 #endif
7386 for (i = 0; i < MAXDESC; i++)
7388 chan_process[i] = Qnil;
7389 proc_buffered_char[i] = -1;
7391 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7392 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7393 #ifdef DATAGRAM_SOCKETS
7394 memset (datagram_address, 0, sizeof datagram_address);
7395 #endif
7398 Lisp_Object subfeatures = Qnil;
7399 const struct socket_options *sopt;
7401 #define ADD_SUBFEATURE(key, val) \
7402 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7404 #ifdef NON_BLOCKING_CONNECT
7405 ADD_SUBFEATURE (QCnowait, Qt);
7406 #endif
7407 #ifdef DATAGRAM_SOCKETS
7408 ADD_SUBFEATURE (QCtype, Qdatagram);
7409 #endif
7410 #ifdef HAVE_SEQPACKET
7411 ADD_SUBFEATURE (QCtype, Qseqpacket);
7412 #endif
7413 #ifdef HAVE_LOCAL_SOCKETS
7414 ADD_SUBFEATURE (QCfamily, Qlocal);
7415 #endif
7416 ADD_SUBFEATURE (QCfamily, Qipv4);
7417 #ifdef AF_INET6
7418 ADD_SUBFEATURE (QCfamily, Qipv6);
7419 #endif
7420 #ifdef HAVE_GETSOCKNAME
7421 ADD_SUBFEATURE (QCservice, Qt);
7422 #endif
7423 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7424 ADD_SUBFEATURE (QCserver, Qt);
7425 #endif
7427 for (sopt = socket_options; sopt->name; sopt++)
7428 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7430 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7433 #if defined (DARWIN_OS)
7434 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7435 processes. As such, we only change the default value. */
7436 if (initialized)
7438 const char *release = get_operating_system_release ();
7439 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7440 && release[1] == '.')) {
7441 Vprocess_connection_type = Qnil;
7444 #endif
7445 #endif /* subprocesses */
7446 kbd_is_on_hold = 0;
7449 void
7450 syms_of_process (void)
7452 #ifdef subprocesses
7454 Qprocessp = intern_c_string ("processp");
7455 staticpro (&Qprocessp);
7456 Qrun = intern_c_string ("run");
7457 staticpro (&Qrun);
7458 Qstop = intern_c_string ("stop");
7459 staticpro (&Qstop);
7460 Qsignal = intern_c_string ("signal");
7461 staticpro (&Qsignal);
7463 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7464 here again.
7466 Qexit = intern_c_string ("exit");
7467 staticpro (&Qexit); */
7469 Qopen = intern_c_string ("open");
7470 staticpro (&Qopen);
7471 Qclosed = intern_c_string ("closed");
7472 staticpro (&Qclosed);
7473 Qconnect = intern_c_string ("connect");
7474 staticpro (&Qconnect);
7475 Qfailed = intern_c_string ("failed");
7476 staticpro (&Qfailed);
7477 Qlisten = intern_c_string ("listen");
7478 staticpro (&Qlisten);
7479 Qlocal = intern_c_string ("local");
7480 staticpro (&Qlocal);
7481 Qipv4 = intern_c_string ("ipv4");
7482 staticpro (&Qipv4);
7483 #ifdef AF_INET6
7484 Qipv6 = intern_c_string ("ipv6");
7485 staticpro (&Qipv6);
7486 #endif
7487 Qdatagram = intern_c_string ("datagram");
7488 staticpro (&Qdatagram);
7489 Qseqpacket = intern_c_string ("seqpacket");
7490 staticpro (&Qseqpacket);
7492 QCport = intern_c_string (":port");
7493 staticpro (&QCport);
7494 QCspeed = intern_c_string (":speed");
7495 staticpro (&QCspeed);
7496 QCprocess = intern_c_string (":process");
7497 staticpro (&QCprocess);
7499 QCbytesize = intern_c_string (":bytesize");
7500 staticpro (&QCbytesize);
7501 QCstopbits = intern_c_string (":stopbits");
7502 staticpro (&QCstopbits);
7503 QCparity = intern_c_string (":parity");
7504 staticpro (&QCparity);
7505 Qodd = intern_c_string ("odd");
7506 staticpro (&Qodd);
7507 Qeven = intern_c_string ("even");
7508 staticpro (&Qeven);
7509 QCflowcontrol = intern_c_string (":flowcontrol");
7510 staticpro (&QCflowcontrol);
7511 Qhw = intern_c_string ("hw");
7512 staticpro (&Qhw);
7513 Qsw = intern_c_string ("sw");
7514 staticpro (&Qsw);
7515 QCsummary = intern_c_string (":summary");
7516 staticpro (&QCsummary);
7518 Qreal = intern_c_string ("real");
7519 staticpro (&Qreal);
7520 Qnetwork = intern_c_string ("network");
7521 staticpro (&Qnetwork);
7522 Qserial = intern_c_string ("serial");
7523 staticpro (&Qserial);
7524 QCbuffer = intern_c_string (":buffer");
7525 staticpro (&QCbuffer);
7526 QChost = intern_c_string (":host");
7527 staticpro (&QChost);
7528 QCservice = intern_c_string (":service");
7529 staticpro (&QCservice);
7530 QClocal = intern_c_string (":local");
7531 staticpro (&QClocal);
7532 QCremote = intern_c_string (":remote");
7533 staticpro (&QCremote);
7534 QCcoding = intern_c_string (":coding");
7535 staticpro (&QCcoding);
7536 QCserver = intern_c_string (":server");
7537 staticpro (&QCserver);
7538 QCnowait = intern_c_string (":nowait");
7539 staticpro (&QCnowait);
7540 QCsentinel = intern_c_string (":sentinel");
7541 staticpro (&QCsentinel);
7542 QClog = intern_c_string (":log");
7543 staticpro (&QClog);
7544 QCnoquery = intern_c_string (":noquery");
7545 staticpro (&QCnoquery);
7546 QCstop = intern_c_string (":stop");
7547 staticpro (&QCstop);
7548 QCoptions = intern_c_string (":options");
7549 staticpro (&QCoptions);
7550 QCplist = intern_c_string (":plist");
7551 staticpro (&QCplist);
7553 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7554 staticpro (&Qlast_nonmenu_event);
7556 staticpro (&Vprocess_alist);
7557 #ifdef SIGCHLD
7558 staticpro (&deleted_pid_list);
7559 #endif
7561 #endif /* subprocesses */
7563 QCname = intern_c_string (":name");
7564 staticpro (&QCname);
7565 QCtype = intern_c_string (":type");
7566 staticpro (&QCtype);
7568 Qeuid = intern_c_string ("euid");
7569 staticpro (&Qeuid);
7570 Qegid = intern_c_string ("egid");
7571 staticpro (&Qegid);
7572 Quser = intern_c_string ("user");
7573 staticpro (&Quser);
7574 Qgroup = intern_c_string ("group");
7575 staticpro (&Qgroup);
7576 Qcomm = intern_c_string ("comm");
7577 staticpro (&Qcomm);
7578 Qstate = intern_c_string ("state");
7579 staticpro (&Qstate);
7580 Qppid = intern_c_string ("ppid");
7581 staticpro (&Qppid);
7582 Qpgrp = intern_c_string ("pgrp");
7583 staticpro (&Qpgrp);
7584 Qsess = intern_c_string ("sess");
7585 staticpro (&Qsess);
7586 Qttname = intern_c_string ("ttname");
7587 staticpro (&Qttname);
7588 Qtpgid = intern_c_string ("tpgid");
7589 staticpro (&Qtpgid);
7590 Qminflt = intern_c_string ("minflt");
7591 staticpro (&Qminflt);
7592 Qmajflt = intern_c_string ("majflt");
7593 staticpro (&Qmajflt);
7594 Qcminflt = intern_c_string ("cminflt");
7595 staticpro (&Qcminflt);
7596 Qcmajflt = intern_c_string ("cmajflt");
7597 staticpro (&Qcmajflt);
7598 Qutime = intern_c_string ("utime");
7599 staticpro (&Qutime);
7600 Qstime = intern_c_string ("stime");
7601 staticpro (&Qstime);
7602 Qtime = intern_c_string ("time");
7603 staticpro (&Qtime);
7604 Qcutime = intern_c_string ("cutime");
7605 staticpro (&Qcutime);
7606 Qcstime = intern_c_string ("cstime");
7607 staticpro (&Qcstime);
7608 Qctime = intern_c_string ("ctime");
7609 staticpro (&Qctime);
7610 Qpri = intern_c_string ("pri");
7611 staticpro (&Qpri);
7612 Qnice = intern_c_string ("nice");
7613 staticpro (&Qnice);
7614 Qthcount = intern_c_string ("thcount");
7615 staticpro (&Qthcount);
7616 Qstart = intern_c_string ("start");
7617 staticpro (&Qstart);
7618 Qvsize = intern_c_string ("vsize");
7619 staticpro (&Qvsize);
7620 Qrss = intern_c_string ("rss");
7621 staticpro (&Qrss);
7622 Qetime = intern_c_string ("etime");
7623 staticpro (&Qetime);
7624 Qpcpu = intern_c_string ("pcpu");
7625 staticpro (&Qpcpu);
7626 Qpmem = intern_c_string ("pmem");
7627 staticpro (&Qpmem);
7628 Qargs = intern_c_string ("args");
7629 staticpro (&Qargs);
7631 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7632 doc: /* *Non-nil means delete processes immediately when they exit.
7633 A value of nil means don't delete them until `list-processes' is run. */);
7635 delete_exited_processes = 1;
7637 #ifdef subprocesses
7638 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7639 doc: /* Control type of device used to communicate with subprocesses.
7640 Values are nil to use a pipe, or t or `pty' to use a pty.
7641 The value has no effect if the system has no ptys or if all ptys are busy:
7642 then a pipe is used in any case.
7643 The value takes effect when `start-process' is called. */);
7644 Vprocess_connection_type = Qt;
7646 #ifdef ADAPTIVE_READ_BUFFERING
7647 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7648 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7649 On some systems, when Emacs reads the output from a subprocess, the output data
7650 is read in very small blocks, potentially resulting in very poor performance.
7651 This behavior can be remedied to some extent by setting this variable to a
7652 non-nil value, as it will automatically delay reading from such processes, to
7653 allow them to produce more output before Emacs tries to read it.
7654 If the value is t, the delay is reset after each write to the process; any other
7655 non-nil value means that the delay is not reset on write.
7656 The variable takes effect when `start-process' is called. */);
7657 Vprocess_adaptive_read_buffering = Qt;
7658 #endif
7660 defsubr (&Sprocessp);
7661 defsubr (&Sget_process);
7662 defsubr (&Sdelete_process);
7663 defsubr (&Sprocess_status);
7664 defsubr (&Sprocess_exit_status);
7665 defsubr (&Sprocess_id);
7666 defsubr (&Sprocess_name);
7667 defsubr (&Sprocess_tty_name);
7668 defsubr (&Sprocess_command);
7669 defsubr (&Sset_process_buffer);
7670 defsubr (&Sprocess_buffer);
7671 defsubr (&Sprocess_mark);
7672 defsubr (&Sset_process_filter);
7673 defsubr (&Sprocess_filter);
7674 defsubr (&Sset_process_sentinel);
7675 defsubr (&Sprocess_sentinel);
7676 defsubr (&Sset_process_window_size);
7677 defsubr (&Sset_process_inherit_coding_system_flag);
7678 defsubr (&Sset_process_query_on_exit_flag);
7679 defsubr (&Sprocess_query_on_exit_flag);
7680 defsubr (&Sprocess_contact);
7681 defsubr (&Sprocess_plist);
7682 defsubr (&Sset_process_plist);
7683 defsubr (&Slist_processes);
7684 defsubr (&Sprocess_list);
7685 defsubr (&Sstart_process);
7686 defsubr (&Sserial_process_configure);
7687 defsubr (&Smake_serial_process);
7688 defsubr (&Sset_network_process_option);
7689 defsubr (&Smake_network_process);
7690 defsubr (&Sformat_network_address);
7691 #if defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7692 #ifdef SIOCGIFCONF
7693 defsubr (&Snetwork_interface_list);
7694 #endif
7695 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7696 defsubr (&Snetwork_interface_info);
7697 #endif
7698 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H) */
7699 #ifdef DATAGRAM_SOCKETS
7700 defsubr (&Sprocess_datagram_address);
7701 defsubr (&Sset_process_datagram_address);
7702 #endif
7703 defsubr (&Saccept_process_output);
7704 defsubr (&Sprocess_send_region);
7705 defsubr (&Sprocess_send_string);
7706 defsubr (&Sinterrupt_process);
7707 defsubr (&Skill_process);
7708 defsubr (&Squit_process);
7709 defsubr (&Sstop_process);
7710 defsubr (&Scontinue_process);
7711 defsubr (&Sprocess_running_child_p);
7712 defsubr (&Sprocess_send_eof);
7713 defsubr (&Ssignal_process);
7714 defsubr (&Swaiting_for_user_input_p);
7715 defsubr (&Sprocess_type);
7716 defsubr (&Sset_process_coding_system);
7717 defsubr (&Sprocess_coding_system);
7718 defsubr (&Sset_process_filter_multibyte);
7719 defsubr (&Sprocess_filter_multibyte_p);
7721 #endif /* subprocesses */
7723 defsubr (&Sget_buffer_process);
7724 defsubr (&Sprocess_inherit_coding_system_flag);
7725 defsubr (&Slist_system_processes);
7726 defsubr (&Sprocess_attributes);
7729 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7730 (do not change this comment) */