]> code.delx.au - gnu-emacs/blob - src/process.c
Merge from emacs-24; up to 2012-12-06T01:39:03Z!monnier@iro.umontreal.ca
[gnu-emacs] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2
3 Copyright (C) 1985-1988, 1993-1996, 1998-1999, 2001-2013 Free Software
4 Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
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.
12
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.
17
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/>. */
20
21
22 #include <config.h>
23
24 #define PROCESS_INLINE EXTERN_INLINE
25
26 #include <stdio.h>
27 #include <errno.h>
28 #include <sys/types.h> /* Some typedefs are used in sys/file.h. */
29 #include <sys/file.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33
34 #include "lisp.h"
35
36 /* Only MS-DOS does not define `subprocesses'. */
37 #ifdef subprocesses
38
39 #include <sys/socket.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43
44 /* Are local (unix) sockets supported? */
45 #if defined (HAVE_SYS_UN_H)
46 #if !defined (AF_LOCAL) && defined (AF_UNIX)
47 #define AF_LOCAL AF_UNIX
48 #endif
49 #ifdef AF_LOCAL
50 #define HAVE_LOCAL_SOCKETS
51 #include <sys/un.h>
52 #endif
53 #endif
54
55 #include <sys/ioctl.h>
56 #if defined (HAVE_NET_IF_H)
57 #include <net/if.h>
58 #endif /* HAVE_NET_IF_H */
59
60 #if defined (HAVE_IFADDRS_H)
61 /* Must be after net/if.h */
62 #include <ifaddrs.h>
63
64 /* We only use structs from this header when we use getifaddrs. */
65 #if defined (HAVE_NET_IF_DL_H)
66 #include <net/if_dl.h>
67 #endif
68
69 #endif
70
71 #ifdef NEED_BSDTTY
72 #include <bsdtty.h>
73 #endif
74
75 #ifdef USG5_4
76 # include <sys/stream.h>
77 # include <sys/stropts.h>
78 #endif
79
80 #ifdef HAVE_RES_INIT
81 #include <netinet/in.h>
82 #include <arpa/nameser.h>
83 #include <resolv.h>
84 #endif
85
86 #ifdef HAVE_UTIL_H
87 #include <util.h>
88 #endif
89
90 #ifdef HAVE_PTY_H
91 #include <pty.h>
92 #endif
93
94 #include <c-ctype.h>
95 #include <sig2str.h>
96
97 #endif /* subprocesses */
98
99 #include "systime.h"
100 #include "systty.h"
101
102 #include "window.h"
103 #include "character.h"
104 #include "buffer.h"
105 #include "coding.h"
106 #include "process.h"
107 #include "frame.h"
108 #include "termhooks.h"
109 #include "termopts.h"
110 #include "commands.h"
111 #include "keyboard.h"
112 #include "blockinput.h"
113 #include "dispextern.h"
114 #include "composite.h"
115 #include "atimer.h"
116 #include "sysselect.h"
117 #include "syssignal.h"
118 #include "syswait.h"
119 #ifdef HAVE_GNUTLS
120 #include "gnutls.h"
121 #endif
122
123 #ifdef HAVE_WINDOW_SYSTEM
124 #include TERM_HEADER
125 #endif /* HAVE_WINDOW_SYSTEM */
126
127 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
128 #include "xgselect.h"
129 #endif
130
131 #ifdef WINDOWSNT
132 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
133 EMACS_TIME *, void *);
134 #endif
135
136 /* Work around GCC 4.7.0 bug with strict overflow checking; see
137 <http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
138 These lines can be removed once the GCC bug is fixed. */
139 #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
140 # pragma GCC diagnostic ignored "-Wstrict-overflow"
141 #endif
142
143 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
144 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
145 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
146 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
147 Lisp_Object QCname, QCtype;
148 \f
149 /* Non-zero if keyboard input is on hold, zero otherwise. */
150
151 static int kbd_is_on_hold;
152
153 /* Nonzero means don't run process sentinels. This is used
154 when exiting. */
155 int inhibit_sentinels;
156
157 #ifdef subprocesses
158
159 Lisp_Object Qprocessp;
160 static Lisp_Object Qrun, Qstop, Qsignal;
161 static Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
162 Lisp_Object Qlocal;
163 static Lisp_Object Qipv4, Qdatagram, Qseqpacket;
164 static Lisp_Object Qreal, Qnetwork, Qserial;
165 #ifdef AF_INET6
166 static Lisp_Object Qipv6;
167 #endif
168 static Lisp_Object QCport, QCprocess;
169 Lisp_Object QCspeed;
170 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
171 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
172 static Lisp_Object QCbuffer, QChost, QCservice;
173 static Lisp_Object QClocal, QCremote, QCcoding;
174 static Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
175 static Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
176 static Lisp_Object Qlast_nonmenu_event;
177
178 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
179 #define NETCONN1_P(p) (EQ (p->type, Qnetwork))
180 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
181 #define SERIALCONN1_P(p) (EQ (p->type, Qserial))
182
183 #ifndef HAVE_H_ERRNO
184 extern int h_errno;
185 #endif
186
187 /* Number of events of change of status of a process. */
188 static EMACS_INT process_tick;
189 /* Number of events for which the user or sentinel has been notified. */
190 static EMACS_INT update_tick;
191
192 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
193
194 /* Only W32 has this, it really means that select can't take write mask. */
195 #ifdef BROKEN_NON_BLOCKING_CONNECT
196 #undef NON_BLOCKING_CONNECT
197 #define SELECT_CANT_DO_WRITE_MASK
198 #else
199 #ifndef NON_BLOCKING_CONNECT
200 #ifdef HAVE_SELECT
201 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
202 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
203 #define NON_BLOCKING_CONNECT
204 #endif /* EWOULDBLOCK || EINPROGRESS */
205 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
206 #endif /* HAVE_SELECT */
207 #endif /* NON_BLOCKING_CONNECT */
208 #endif /* BROKEN_NON_BLOCKING_CONNECT */
209
210 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
211 this system. We need to read full packets, so we need a
212 "non-destructive" select. So we require either native select,
213 or emulation of select using FIONREAD. */
214
215 #ifndef BROKEN_DATAGRAM_SOCKETS
216 # if defined HAVE_SELECT || defined USABLE_FIONREAD
217 # if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
218 # define DATAGRAM_SOCKETS
219 # endif
220 # endif
221 #endif
222
223 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
224 # define HAVE_SEQPACKET
225 #endif
226
227 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
228 #define ADAPTIVE_READ_BUFFERING
229 #endif
230
231 #ifdef ADAPTIVE_READ_BUFFERING
232 #define READ_OUTPUT_DELAY_INCREMENT (EMACS_TIME_RESOLUTION / 100)
233 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
234 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
235
236 /* Number of processes which have a non-zero read_output_delay,
237 and therefore might be delayed for adaptive read buffering. */
238
239 static int process_output_delay_count;
240
241 /* Non-zero if any process has non-nil read_output_skip. */
242
243 static int process_output_skip;
244
245 #else
246 #define process_output_delay_count 0
247 #endif
248
249 static void create_process (Lisp_Object, char **, Lisp_Object);
250 #ifdef USABLE_SIGIO
251 static int keyboard_bit_set (SELECT_TYPE *);
252 #endif
253 static void deactivate_process (Lisp_Object);
254 static void status_notify (struct Lisp_Process *);
255 static int read_process_output (Lisp_Object, int);
256 static void handle_child_signal (int);
257 static void create_pty (Lisp_Object);
258
259 /* If we support a window system, turn on the code to poll periodically
260 to detect C-g. It isn't actually used when doing interrupt input. */
261 #ifdef HAVE_WINDOW_SYSTEM
262 #define POLL_FOR_INPUT
263 #endif
264
265 static Lisp_Object get_process (register Lisp_Object name);
266 static void exec_sentinel (Lisp_Object proc, Lisp_Object reason);
267
268 /* Mask of bits indicating the descriptors that we wait for input on. */
269
270 static SELECT_TYPE input_wait_mask;
271
272 /* Mask that excludes keyboard input descriptor(s). */
273
274 static SELECT_TYPE non_keyboard_wait_mask;
275
276 /* Mask that excludes process input descriptor(s). */
277
278 static SELECT_TYPE non_process_wait_mask;
279
280 /* Mask for selecting for write. */
281
282 static SELECT_TYPE write_mask;
283
284 #ifdef NON_BLOCKING_CONNECT
285 /* Mask of bits indicating the descriptors that we wait for connect to
286 complete on. Once they complete, they are removed from this mask
287 and added to the input_wait_mask and non_keyboard_wait_mask. */
288
289 static SELECT_TYPE connect_wait_mask;
290
291 /* Number of bits set in connect_wait_mask. */
292 static int num_pending_connects;
293 #endif /* NON_BLOCKING_CONNECT */
294
295 /* The largest descriptor currently in use for a process object. */
296 static int max_process_desc;
297
298 /* The largest descriptor currently in use for input. */
299 static int max_input_desc;
300
301 /* Indexed by descriptor, gives the process (if any) for that descriptor */
302 static Lisp_Object chan_process[MAXDESC];
303
304 /* Alist of elements (NAME . PROCESS) */
305 static Lisp_Object Vprocess_alist;
306
307 /* Buffered-ahead input char from process, indexed by channel.
308 -1 means empty (no char is buffered).
309 Used on sys V where the only way to tell if there is any
310 output from the process is to read at least one char.
311 Always -1 on systems that support FIONREAD. */
312
313 static int proc_buffered_char[MAXDESC];
314
315 /* Table of `struct coding-system' for each process. */
316 static struct coding_system *proc_decode_coding_system[MAXDESC];
317 static struct coding_system *proc_encode_coding_system[MAXDESC];
318
319 #ifdef DATAGRAM_SOCKETS
320 /* Table of `partner address' for datagram sockets. */
321 static struct sockaddr_and_len {
322 struct sockaddr *sa;
323 int len;
324 } datagram_address[MAXDESC];
325 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
326 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
327 #else
328 #define DATAGRAM_CHAN_P(chan) (0)
329 #define DATAGRAM_CONN_P(proc) (0)
330 #endif
331
332 /* These setters are used only in this file, so they can be private. */
333 static void
334 pset_buffer (struct Lisp_Process *p, Lisp_Object val)
335 {
336 p->buffer = val;
337 }
338 static void
339 pset_command (struct Lisp_Process *p, Lisp_Object val)
340 {
341 p->command = val;
342 }
343 static void
344 pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
345 {
346 p->decode_coding_system = val;
347 }
348 static void
349 pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
350 {
351 p->decoding_buf = val;
352 }
353 static void
354 pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
355 {
356 p->encode_coding_system = val;
357 }
358 static void
359 pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
360 {
361 p->encoding_buf = val;
362 }
363 static void
364 pset_filter (struct Lisp_Process *p, Lisp_Object val)
365 {
366 p->filter = val;
367 }
368 static void
369 pset_log (struct Lisp_Process *p, Lisp_Object val)
370 {
371 p->log = val;
372 }
373 static void
374 pset_mark (struct Lisp_Process *p, Lisp_Object val)
375 {
376 p->mark = val;
377 }
378 static void
379 pset_name (struct Lisp_Process *p, Lisp_Object val)
380 {
381 p->name = val;
382 }
383 static void
384 pset_plist (struct Lisp_Process *p, Lisp_Object val)
385 {
386 p->plist = val;
387 }
388 static void
389 pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
390 {
391 p->sentinel = val;
392 }
393 static void
394 pset_status (struct Lisp_Process *p, Lisp_Object val)
395 {
396 p->status = val;
397 }
398 static void
399 pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
400 {
401 p->tty_name = val;
402 }
403 static void
404 pset_type (struct Lisp_Process *p, Lisp_Object val)
405 {
406 p->type = val;
407 }
408 static void
409 pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
410 {
411 p->write_queue = val;
412 }
413
414 \f
415
416 static struct fd_callback_data
417 {
418 fd_callback func;
419 void *data;
420 #define FOR_READ 1
421 #define FOR_WRITE 2
422 int condition; /* mask of the defines above. */
423 } fd_callback_info[MAXDESC];
424
425
426 /* Add a file descriptor FD to be monitored for when read is possible.
427 When read is possible, call FUNC with argument DATA. */
428
429 void
430 add_read_fd (int fd, fd_callback func, void *data)
431 {
432 eassert (fd < MAXDESC);
433 add_keyboard_wait_descriptor (fd);
434
435 fd_callback_info[fd].func = func;
436 fd_callback_info[fd].data = data;
437 fd_callback_info[fd].condition |= FOR_READ;
438 }
439
440 /* Stop monitoring file descriptor FD for when read is possible. */
441
442 void
443 delete_read_fd (int fd)
444 {
445 eassert (fd < MAXDESC);
446 delete_keyboard_wait_descriptor (fd);
447
448 fd_callback_info[fd].condition &= ~FOR_READ;
449 if (fd_callback_info[fd].condition == 0)
450 {
451 fd_callback_info[fd].func = 0;
452 fd_callback_info[fd].data = 0;
453 }
454 }
455
456 /* Add a file descriptor FD to be monitored for when write is possible.
457 When write is possible, call FUNC with argument DATA. */
458
459 void
460 add_write_fd (int fd, fd_callback func, void *data)
461 {
462 eassert (fd < MAXDESC);
463 FD_SET (fd, &write_mask);
464 if (fd > max_input_desc)
465 max_input_desc = fd;
466
467 fd_callback_info[fd].func = func;
468 fd_callback_info[fd].data = data;
469 fd_callback_info[fd].condition |= FOR_WRITE;
470 }
471
472 /* Stop monitoring file descriptor FD for when write is possible. */
473
474 void
475 delete_write_fd (int fd)
476 {
477 int lim = max_input_desc;
478
479 eassert (fd < MAXDESC);
480 FD_CLR (fd, &write_mask);
481 fd_callback_info[fd].condition &= ~FOR_WRITE;
482 if (fd_callback_info[fd].condition == 0)
483 {
484 fd_callback_info[fd].func = 0;
485 fd_callback_info[fd].data = 0;
486
487 if (fd == max_input_desc)
488 for (fd = lim; fd >= 0; fd--)
489 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
490 {
491 max_input_desc = fd;
492 break;
493 }
494
495 }
496 }
497
498 \f
499 /* Compute the Lisp form of the process status, p->status, from
500 the numeric status that was returned by `wait'. */
501
502 static Lisp_Object status_convert (int);
503
504 static void
505 update_status (struct Lisp_Process *p)
506 {
507 eassert (p->raw_status_new);
508 pset_status (p, status_convert (p->raw_status));
509 p->raw_status_new = 0;
510 }
511
512 /* Convert a process status word in Unix format to
513 the list that we use internally. */
514
515 static Lisp_Object
516 status_convert (int w)
517 {
518 if (WIFSTOPPED (w))
519 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
520 else if (WIFEXITED (w))
521 return Fcons (Qexit, Fcons (make_number (WEXITSTATUS (w)),
522 WCOREDUMP (w) ? Qt : Qnil));
523 else if (WIFSIGNALED (w))
524 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
525 WCOREDUMP (w) ? Qt : Qnil));
526 else
527 return Qrun;
528 }
529
530 /* Given a status-list, extract the three pieces of information
531 and store them individually through the three pointers. */
532
533 static void
534 decode_status (Lisp_Object l, Lisp_Object *symbol, int *code, int *coredump)
535 {
536 Lisp_Object tem;
537
538 if (SYMBOLP (l))
539 {
540 *symbol = l;
541 *code = 0;
542 *coredump = 0;
543 }
544 else
545 {
546 *symbol = XCAR (l);
547 tem = XCDR (l);
548 *code = XFASTINT (XCAR (tem));
549 tem = XCDR (tem);
550 *coredump = !NILP (tem);
551 }
552 }
553
554 /* Return a string describing a process status list. */
555
556 static Lisp_Object
557 status_message (struct Lisp_Process *p)
558 {
559 Lisp_Object status = p->status;
560 Lisp_Object symbol;
561 int code, coredump;
562 Lisp_Object string, string2;
563
564 decode_status (status, &symbol, &code, &coredump);
565
566 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
567 {
568 char const *signame;
569 synchronize_system_messages_locale ();
570 signame = strsignal (code);
571 if (signame == 0)
572 string = build_string ("unknown");
573 else
574 {
575 int c1, c2;
576
577 string = build_unibyte_string (signame);
578 if (! NILP (Vlocale_coding_system))
579 string = (code_convert_string_norecord
580 (string, Vlocale_coding_system, 0));
581 c1 = STRING_CHAR (SDATA (string));
582 c2 = downcase (c1);
583 if (c1 != c2)
584 Faset (string, make_number (0), make_number (c2));
585 }
586 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
587 return concat2 (string, string2);
588 }
589 else if (EQ (symbol, Qexit))
590 {
591 if (NETCONN1_P (p))
592 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
593 if (code == 0)
594 return build_string ("finished\n");
595 string = Fnumber_to_string (make_number (code));
596 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
597 return concat3 (build_string ("exited abnormally with code "),
598 string, string2);
599 }
600 else if (EQ (symbol, Qfailed))
601 {
602 string = Fnumber_to_string (make_number (code));
603 string2 = build_string ("\n");
604 return concat3 (build_string ("failed with code "),
605 string, string2);
606 }
607 else
608 return Fcopy_sequence (Fsymbol_name (symbol));
609 }
610 \f
611 #ifdef HAVE_PTYS
612
613 /* The file name of the pty opened by allocate_pty. */
614 static char pty_name[24];
615
616 /* Open an available pty, returning a file descriptor.
617 Return -1 on failure.
618 The file name of the terminal corresponding to the pty
619 is left in the variable pty_name. */
620
621 static int
622 allocate_pty (void)
623 {
624 int fd;
625
626 #ifdef PTY_ITERATION
627 PTY_ITERATION
628 #else
629 register int c, i;
630 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
631 for (i = 0; i < 16; i++)
632 #endif
633 {
634 #ifdef PTY_NAME_SPRINTF
635 PTY_NAME_SPRINTF
636 #else
637 sprintf (pty_name, "/dev/pty%c%x", c, i);
638 #endif /* no PTY_NAME_SPRINTF */
639
640 #ifdef PTY_OPEN
641 PTY_OPEN;
642 #else /* no PTY_OPEN */
643 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
644 #endif /* no PTY_OPEN */
645
646 if (fd >= 0)
647 {
648 /* check to make certain that both sides are available
649 this avoids a nasty yet stupid bug in rlogins */
650 #ifdef PTY_TTY_NAME_SPRINTF
651 PTY_TTY_NAME_SPRINTF
652 #else
653 sprintf (pty_name, "/dev/tty%c%x", c, i);
654 #endif /* no PTY_TTY_NAME_SPRINTF */
655 if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
656 {
657 emacs_close (fd);
658 # ifndef __sgi
659 continue;
660 # else
661 return -1;
662 # endif /* __sgi */
663 }
664 setup_pty (fd);
665 return fd;
666 }
667 }
668 return -1;
669 }
670 #endif /* HAVE_PTYS */
671 \f
672 static Lisp_Object
673 make_process (Lisp_Object name)
674 {
675 register Lisp_Object val, tem, name1;
676 register struct Lisp_Process *p;
677 char suffix[sizeof "<>" + INT_STRLEN_BOUND (printmax_t)];
678 printmax_t i;
679
680 p = allocate_process ();
681 /* Initialize Lisp data. Note that allocate_process initializes all
682 Lisp data to nil, so do it only for slots which should not be nil. */
683 pset_status (p, Qrun);
684 pset_mark (p, Fmake_marker ());
685
686 /* Initialize non-Lisp data. Note that allocate_process zeroes out all
687 non-Lisp data, so do it only for slots which should not be zero. */
688 p->infd = -1;
689 p->outfd = -1;
690
691 #ifdef HAVE_GNUTLS
692 p->gnutls_initstage = GNUTLS_STAGE_EMPTY;
693 #endif
694
695 /* If name is already in use, modify it until it is unused. */
696
697 name1 = name;
698 for (i = 1; ; i++)
699 {
700 tem = Fget_process (name1);
701 if (NILP (tem)) break;
702 name1 = concat2 (name, make_formatted_string (suffix, "<%"pMd">", i));
703 }
704 name = name1;
705 pset_name (p, name);
706 XSETPROCESS (val, p);
707 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
708 return val;
709 }
710
711 static void
712 remove_process (register Lisp_Object proc)
713 {
714 register Lisp_Object pair;
715
716 pair = Frassq (proc, Vprocess_alist);
717 Vprocess_alist = Fdelq (pair, Vprocess_alist);
718
719 deactivate_process (proc);
720 }
721
722 \f
723 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
724 doc: /* Return t if OBJECT is a process. */)
725 (Lisp_Object object)
726 {
727 return PROCESSP (object) ? Qt : Qnil;
728 }
729
730 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
731 doc: /* Return the process named NAME, or nil if there is none. */)
732 (register Lisp_Object name)
733 {
734 if (PROCESSP (name))
735 return name;
736 CHECK_STRING (name);
737 return Fcdr (Fassoc (name, Vprocess_alist));
738 }
739
740 /* This is how commands for the user decode process arguments. It
741 accepts a process, a process name, a buffer, a buffer name, or nil.
742 Buffers denote the first process in the buffer, and nil denotes the
743 current buffer. */
744
745 static Lisp_Object
746 get_process (register Lisp_Object name)
747 {
748 register Lisp_Object proc, obj;
749 if (STRINGP (name))
750 {
751 obj = Fget_process (name);
752 if (NILP (obj))
753 obj = Fget_buffer (name);
754 if (NILP (obj))
755 error ("Process %s does not exist", SDATA (name));
756 }
757 else if (NILP (name))
758 obj = Fcurrent_buffer ();
759 else
760 obj = name;
761
762 /* Now obj should be either a buffer object or a process object.
763 */
764 if (BUFFERP (obj))
765 {
766 proc = Fget_buffer_process (obj);
767 if (NILP (proc))
768 error ("Buffer %s has no process", SDATA (BVAR (XBUFFER (obj), name)));
769 }
770 else
771 {
772 CHECK_PROCESS (obj);
773 proc = obj;
774 }
775 return proc;
776 }
777
778
779 /* Fdelete_process promises to immediately forget about the process, but in
780 reality, Emacs needs to remember those processes until they have been
781 treated by the SIGCHLD handler and waitpid has been invoked on them;
782 otherwise they might fill up the kernel's process table.
783
784 Some processes created by call-process are also put onto this list. */
785 static Lisp_Object deleted_pid_list;
786
787 void
788 record_deleted_pid (pid_t pid)
789 {
790 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
791 /* GC treated elements set to nil. */
792 Fdelq (Qnil, deleted_pid_list));
793
794 }
795
796 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
797 doc: /* Delete PROCESS: kill it and forget about it immediately.
798 PROCESS may be a process, a buffer, the name of a process or buffer, or
799 nil, indicating the current buffer's process. */)
800 (register Lisp_Object process)
801 {
802 register struct Lisp_Process *p;
803
804 process = get_process (process);
805 p = XPROCESS (process);
806
807 p->raw_status_new = 0;
808 if (NETCONN1_P (p) || SERIALCONN1_P (p))
809 {
810 pset_status (p, Fcons (Qexit, Fcons (make_number (0), Qnil)));
811 p->tick = ++process_tick;
812 status_notify (p);
813 redisplay_preserve_echo_area (13);
814 }
815 else
816 {
817 if (p->alive)
818 record_kill_process (p);
819
820 if (p->infd >= 0)
821 {
822 /* Update P's status, since record_kill_process will make the
823 SIGCHLD handler update deleted_pid_list, not *P. */
824 Lisp_Object symbol;
825 if (p->raw_status_new)
826 update_status (p);
827 symbol = CONSP (p->status) ? XCAR (p->status) : p->status;
828 if (! (EQ (symbol, Qsignal) || EQ (symbol, Qexit)))
829 pset_status (p, list2 (Qsignal, make_number (SIGKILL)));
830
831 p->tick = ++process_tick;
832 status_notify (p);
833 redisplay_preserve_echo_area (13);
834 }
835 }
836 remove_process (process);
837 return Qnil;
838 }
839 \f
840 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
841 doc: /* Return the status of PROCESS.
842 The returned value is one of the following symbols:
843 run -- for a process that is running.
844 stop -- for a process stopped but continuable.
845 exit -- for a process that has exited.
846 signal -- for a process that has got a fatal signal.
847 open -- for a network stream connection that is open.
848 listen -- for a network stream server that is listening.
849 closed -- for a network stream connection that is closed.
850 connect -- when waiting for a non-blocking connection to complete.
851 failed -- when a non-blocking connection has failed.
852 nil -- if arg is a process name and no such process exists.
853 PROCESS may be a process, a buffer, the name of a process, or
854 nil, indicating the current buffer's process. */)
855 (register Lisp_Object process)
856 {
857 register struct Lisp_Process *p;
858 register Lisp_Object status;
859
860 if (STRINGP (process))
861 process = Fget_process (process);
862 else
863 process = get_process (process);
864
865 if (NILP (process))
866 return process;
867
868 p = XPROCESS (process);
869 if (p->raw_status_new)
870 update_status (p);
871 status = p->status;
872 if (CONSP (status))
873 status = XCAR (status);
874 if (NETCONN1_P (p) || SERIALCONN1_P (p))
875 {
876 if (EQ (status, Qexit))
877 status = Qclosed;
878 else if (EQ (p->command, Qt))
879 status = Qstop;
880 else if (EQ (status, Qrun))
881 status = Qopen;
882 }
883 return status;
884 }
885
886 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
887 1, 1, 0,
888 doc: /* Return the exit status of PROCESS or the signal number that killed it.
889 If PROCESS has not yet exited or died, return 0. */)
890 (register Lisp_Object process)
891 {
892 CHECK_PROCESS (process);
893 if (XPROCESS (process)->raw_status_new)
894 update_status (XPROCESS (process));
895 if (CONSP (XPROCESS (process)->status))
896 return XCAR (XCDR (XPROCESS (process)->status));
897 return make_number (0);
898 }
899
900 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
901 doc: /* Return the process id of PROCESS.
902 This is the pid of the external process which PROCESS uses or talks to.
903 For a network connection, this value is nil. */)
904 (register Lisp_Object process)
905 {
906 pid_t pid;
907
908 CHECK_PROCESS (process);
909 pid = XPROCESS (process)->pid;
910 return (pid ? make_fixnum_or_float (pid) : Qnil);
911 }
912
913 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
914 doc: /* Return the name of PROCESS, as a string.
915 This is the name of the program invoked in PROCESS,
916 possibly modified to make it unique among process names. */)
917 (register Lisp_Object process)
918 {
919 CHECK_PROCESS (process);
920 return XPROCESS (process)->name;
921 }
922
923 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
924 doc: /* Return the command that was executed to start PROCESS.
925 This is a list of strings, the first string being the program executed
926 and the rest of the strings being the arguments given to it.
927 For a network or serial process, this is nil (process is running) or t
928 \(process is stopped). */)
929 (register Lisp_Object process)
930 {
931 CHECK_PROCESS (process);
932 return XPROCESS (process)->command;
933 }
934
935 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
936 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
937 This is the terminal that the process itself reads and writes on,
938 not the name of the pty that Emacs uses to talk with that terminal. */)
939 (register Lisp_Object process)
940 {
941 CHECK_PROCESS (process);
942 return XPROCESS (process)->tty_name;
943 }
944
945 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
946 2, 2, 0,
947 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil).
948 Return BUFFER. */)
949 (register Lisp_Object process, Lisp_Object buffer)
950 {
951 struct Lisp_Process *p;
952
953 CHECK_PROCESS (process);
954 if (!NILP (buffer))
955 CHECK_BUFFER (buffer);
956 p = XPROCESS (process);
957 pset_buffer (p, buffer);
958 if (NETCONN1_P (p) || SERIALCONN1_P (p))
959 pset_childp (p, Fplist_put (p->childp, QCbuffer, buffer));
960 setup_process_coding_systems (process);
961 return buffer;
962 }
963
964 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
965 1, 1, 0,
966 doc: /* Return the buffer PROCESS is associated with.
967 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
968 (register Lisp_Object process)
969 {
970 CHECK_PROCESS (process);
971 return XPROCESS (process)->buffer;
972 }
973
974 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
975 1, 1, 0,
976 doc: /* Return the marker for the end of the last output from PROCESS. */)
977 (register Lisp_Object process)
978 {
979 CHECK_PROCESS (process);
980 return XPROCESS (process)->mark;
981 }
982
983 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
984 2, 2, 0,
985 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
986 A value of t means stop accepting output from the process.
987
988 When a process has a filter, its buffer is not used for output.
989 Instead, each time it does output, the entire string of output is
990 passed to the filter.
991
992 The filter gets two arguments: the process and the string of output.
993 The string argument is normally a multibyte string, except:
994 - if the process' input coding system is no-conversion or raw-text,
995 it is a unibyte string (the non-converted input), or else
996 - if `default-enable-multibyte-characters' is nil, it is a unibyte
997 string (the result of converting the decoded input multibyte
998 string to unibyte with `string-make-unibyte'). */)
999 (register Lisp_Object process, Lisp_Object filter)
1000 {
1001 struct Lisp_Process *p;
1002
1003 CHECK_PROCESS (process);
1004 p = XPROCESS (process);
1005
1006 /* Don't signal an error if the process' input file descriptor
1007 is closed. This could make debugging Lisp more difficult,
1008 for example when doing something like
1009
1010 (setq process (start-process ...))
1011 (debug)
1012 (set-process-filter process ...) */
1013
1014 if (p->infd >= 0)
1015 {
1016 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1017 {
1018 FD_CLR (p->infd, &input_wait_mask);
1019 FD_CLR (p->infd, &non_keyboard_wait_mask);
1020 }
1021 else if (EQ (p->filter, Qt)
1022 /* Network or serial process not stopped: */
1023 && !EQ (p->command, Qt))
1024 {
1025 FD_SET (p->infd, &input_wait_mask);
1026 FD_SET (p->infd, &non_keyboard_wait_mask);
1027 }
1028 }
1029
1030 pset_filter (p, filter);
1031 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1032 pset_childp (p, Fplist_put (p->childp, QCfilter, filter));
1033 setup_process_coding_systems (process);
1034 return filter;
1035 }
1036
1037 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1038 1, 1, 0,
1039 doc: /* Returns the filter function of PROCESS; nil if none.
1040 See `set-process-filter' for more info on filter functions. */)
1041 (register Lisp_Object process)
1042 {
1043 CHECK_PROCESS (process);
1044 return XPROCESS (process)->filter;
1045 }
1046
1047 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1048 2, 2, 0,
1049 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1050 The sentinel is called as a function when the process changes state.
1051 It gets two arguments: the process, and a string describing the change. */)
1052 (register Lisp_Object process, Lisp_Object sentinel)
1053 {
1054 struct Lisp_Process *p;
1055
1056 CHECK_PROCESS (process);
1057 p = XPROCESS (process);
1058
1059 pset_sentinel (p, sentinel);
1060 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1061 pset_childp (p, Fplist_put (p->childp, QCsentinel, sentinel));
1062 return sentinel;
1063 }
1064
1065 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1066 1, 1, 0,
1067 doc: /* Return the sentinel of PROCESS; nil if none.
1068 See `set-process-sentinel' for more info on sentinels. */)
1069 (register Lisp_Object process)
1070 {
1071 CHECK_PROCESS (process);
1072 return XPROCESS (process)->sentinel;
1073 }
1074
1075 DEFUN ("set-process-window-size", Fset_process_window_size,
1076 Sset_process_window_size, 3, 3, 0,
1077 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1078 (register Lisp_Object process, Lisp_Object height, Lisp_Object width)
1079 {
1080 CHECK_PROCESS (process);
1081 CHECK_RANGED_INTEGER (height, 0, INT_MAX);
1082 CHECK_RANGED_INTEGER (width, 0, INT_MAX);
1083
1084 if (XPROCESS (process)->infd < 0
1085 || set_window_size (XPROCESS (process)->infd,
1086 XINT (height), XINT (width)) <= 0)
1087 return Qnil;
1088 else
1089 return Qt;
1090 }
1091
1092 DEFUN ("set-process-inherit-coding-system-flag",
1093 Fset_process_inherit_coding_system_flag,
1094 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1095 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1096 If the second argument FLAG is non-nil, then the variable
1097 `buffer-file-coding-system' of the buffer associated with PROCESS
1098 will be bound to the value of the coding system used to decode
1099 the process output.
1100
1101 This is useful when the coding system specified for the process buffer
1102 leaves either the character code conversion or the end-of-line conversion
1103 unspecified, or if the coding system used to decode the process output
1104 is more appropriate for saving the process buffer.
1105
1106 Binding the variable `inherit-process-coding-system' to non-nil before
1107 starting the process is an alternative way of setting the inherit flag
1108 for the process which will run.
1109
1110 This function returns FLAG. */)
1111 (register Lisp_Object process, Lisp_Object flag)
1112 {
1113 CHECK_PROCESS (process);
1114 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1115 return flag;
1116 }
1117
1118 DEFUN ("set-process-query-on-exit-flag",
1119 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1120 2, 2, 0,
1121 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1122 If the second argument FLAG is non-nil, Emacs will query the user before
1123 exiting or killing a buffer if PROCESS is running. This function
1124 returns FLAG. */)
1125 (register Lisp_Object process, Lisp_Object flag)
1126 {
1127 CHECK_PROCESS (process);
1128 XPROCESS (process)->kill_without_query = NILP (flag);
1129 return flag;
1130 }
1131
1132 DEFUN ("process-query-on-exit-flag",
1133 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1134 1, 1, 0,
1135 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1136 (register Lisp_Object process)
1137 {
1138 CHECK_PROCESS (process);
1139 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1140 }
1141
1142 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1143 1, 2, 0,
1144 doc: /* Return the contact info of PROCESS; t for a real child.
1145 For a network or serial connection, the value depends on the optional
1146 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1147 SERVICE) for a network connection or (PORT SPEED) for a serial
1148 connection. If KEY is t, the complete contact information for the
1149 connection is returned, else the specific value for the keyword KEY is
1150 returned. See `make-network-process' or `make-serial-process' for a
1151 list of keywords. */)
1152 (register Lisp_Object process, Lisp_Object key)
1153 {
1154 Lisp_Object contact;
1155
1156 CHECK_PROCESS (process);
1157 contact = XPROCESS (process)->childp;
1158
1159 #ifdef DATAGRAM_SOCKETS
1160 if (DATAGRAM_CONN_P (process)
1161 && (EQ (key, Qt) || EQ (key, QCremote)))
1162 contact = Fplist_put (contact, QCremote,
1163 Fprocess_datagram_address (process));
1164 #endif
1165
1166 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1167 return contact;
1168 if (NILP (key) && NETCONN_P (process))
1169 return Fcons (Fplist_get (contact, QChost),
1170 Fcons (Fplist_get (contact, QCservice), Qnil));
1171 if (NILP (key) && SERIALCONN_P (process))
1172 return Fcons (Fplist_get (contact, QCport),
1173 Fcons (Fplist_get (contact, QCspeed), Qnil));
1174 return Fplist_get (contact, key);
1175 }
1176
1177 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1178 1, 1, 0,
1179 doc: /* Return the plist of PROCESS. */)
1180 (register Lisp_Object process)
1181 {
1182 CHECK_PROCESS (process);
1183 return XPROCESS (process)->plist;
1184 }
1185
1186 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1187 2, 2, 0,
1188 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1189 (register Lisp_Object process, Lisp_Object plist)
1190 {
1191 CHECK_PROCESS (process);
1192 CHECK_LIST (plist);
1193
1194 pset_plist (XPROCESS (process), plist);
1195 return plist;
1196 }
1197
1198 #if 0 /* Turned off because we don't currently record this info
1199 in the process. Perhaps add it. */
1200 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1201 doc: /* Return the connection type of PROCESS.
1202 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1203 a socket connection. */)
1204 (Lisp_Object process)
1205 {
1206 return XPROCESS (process)->type;
1207 }
1208 #endif
1209
1210 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1211 doc: /* Return the connection type of PROCESS.
1212 The value is either the symbol `real', `network', or `serial'.
1213 PROCESS may be a process, a buffer, the name of a process or buffer, or
1214 nil, indicating the current buffer's process. */)
1215 (Lisp_Object process)
1216 {
1217 Lisp_Object proc;
1218 proc = get_process (process);
1219 return XPROCESS (proc)->type;
1220 }
1221
1222 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1223 1, 2, 0,
1224 doc: /* Convert network ADDRESS from internal format to a string.
1225 A 4 or 5 element vector represents an IPv4 address (with port number).
1226 An 8 or 9 element vector represents an IPv6 address (with port number).
1227 If optional second argument OMIT-PORT is non-nil, don't include a port
1228 number in the string, even when present in ADDRESS.
1229 Returns nil if format of ADDRESS is invalid. */)
1230 (Lisp_Object address, Lisp_Object omit_port)
1231 {
1232 if (NILP (address))
1233 return Qnil;
1234
1235 if (STRINGP (address)) /* AF_LOCAL */
1236 return address;
1237
1238 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1239 {
1240 register struct Lisp_Vector *p = XVECTOR (address);
1241 ptrdiff_t size = p->header.size;
1242 Lisp_Object args[10];
1243 int nargs, i;
1244
1245 if (size == 4 || (size == 5 && !NILP (omit_port)))
1246 {
1247 args[0] = build_string ("%d.%d.%d.%d");
1248 nargs = 4;
1249 }
1250 else if (size == 5)
1251 {
1252 args[0] = build_string ("%d.%d.%d.%d:%d");
1253 nargs = 5;
1254 }
1255 else if (size == 8 || (size == 9 && !NILP (omit_port)))
1256 {
1257 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1258 nargs = 8;
1259 }
1260 else if (size == 9)
1261 {
1262 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1263 nargs = 9;
1264 }
1265 else
1266 return Qnil;
1267
1268 for (i = 0; i < nargs; i++)
1269 {
1270 if (! RANGED_INTEGERP (0, p->contents[i], 65535))
1271 return Qnil;
1272
1273 if (nargs <= 5 /* IPv4 */
1274 && i < 4 /* host, not port */
1275 && XINT (p->contents[i]) > 255)
1276 return Qnil;
1277
1278 args[i+1] = p->contents[i];
1279 }
1280
1281 return Fformat (nargs+1, args);
1282 }
1283
1284 if (CONSP (address))
1285 {
1286 Lisp_Object args[2];
1287 args[0] = build_string ("<Family %d>");
1288 args[1] = Fcar (address);
1289 return Fformat (2, args);
1290 }
1291
1292 return Qnil;
1293 }
1294
1295 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1296 doc: /* Return a list of all processes. */)
1297 (void)
1298 {
1299 return Fmapcar (Qcdr, Vprocess_alist);
1300 }
1301 \f
1302 /* Starting asynchronous inferior processes. */
1303
1304 static Lisp_Object start_process_unwind (Lisp_Object proc);
1305
1306 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1307 doc: /* Start a program in a subprocess. Return the process object for it.
1308 NAME is name for process. It is modified if necessary to make it unique.
1309 BUFFER is the buffer (or buffer name) to associate with the process.
1310
1311 Process output (both standard output and standard error streams) goes
1312 at end of BUFFER, unless you specify an output stream or filter
1313 function to handle the output. BUFFER may also be nil, meaning that
1314 this process is not associated with any buffer.
1315
1316 PROGRAM is the program file name. It is searched for in `exec-path'
1317 (which see). If nil, just associate a pty with the buffer. Remaining
1318 arguments are strings to give program as arguments.
1319
1320 If you want to separate standard output from standard error, invoke
1321 the command through a shell and redirect one of them using the shell
1322 syntax.
1323
1324 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1325 (ptrdiff_t nargs, Lisp_Object *args)
1326 {
1327 Lisp_Object buffer, name, program, proc, current_dir, tem;
1328 register unsigned char **new_argv;
1329 ptrdiff_t i;
1330 ptrdiff_t count = SPECPDL_INDEX ();
1331
1332 buffer = args[1];
1333 if (!NILP (buffer))
1334 buffer = Fget_buffer_create (buffer);
1335
1336 /* Make sure that the child will be able to chdir to the current
1337 buffer's current directory, or its unhandled equivalent. We
1338 can't just have the child check for an error when it does the
1339 chdir, since it's in a vfork.
1340
1341 We have to GCPRO around this because Fexpand_file_name and
1342 Funhandled_file_name_directory might call a file name handling
1343 function. The argument list is protected by the caller, so all
1344 we really have to worry about is buffer. */
1345 {
1346 struct gcpro gcpro1, gcpro2;
1347
1348 current_dir = BVAR (current_buffer, directory);
1349
1350 GCPRO2 (buffer, current_dir);
1351
1352 current_dir = Funhandled_file_name_directory (current_dir);
1353 if (NILP (current_dir))
1354 /* If the file name handler says that current_dir is unreachable, use
1355 a sensible default. */
1356 current_dir = build_string ("~/");
1357 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1358 if (NILP (Ffile_accessible_directory_p (current_dir)))
1359 report_file_error ("Setting current directory",
1360 Fcons (BVAR (current_buffer, directory), Qnil));
1361
1362 UNGCPRO;
1363 }
1364
1365 name = args[0];
1366 CHECK_STRING (name);
1367
1368 program = args[2];
1369
1370 if (!NILP (program))
1371 CHECK_STRING (program);
1372
1373 proc = make_process (name);
1374 /* If an error occurs and we can't start the process, we want to
1375 remove it from the process list. This means that each error
1376 check in create_process doesn't need to call remove_process
1377 itself; it's all taken care of here. */
1378 record_unwind_protect (start_process_unwind, proc);
1379
1380 pset_childp (XPROCESS (proc), Qt);
1381 pset_plist (XPROCESS (proc), Qnil);
1382 pset_type (XPROCESS (proc), Qreal);
1383 pset_buffer (XPROCESS (proc), buffer);
1384 pset_sentinel (XPROCESS (proc), Qnil);
1385 pset_filter (XPROCESS (proc), Qnil);
1386 pset_command (XPROCESS (proc), Flist (nargs - 2, args + 2));
1387
1388 #ifdef HAVE_GNUTLS
1389 /* AKA GNUTLS_INITSTAGE(proc). */
1390 XPROCESS (proc)->gnutls_initstage = GNUTLS_STAGE_EMPTY;
1391 pset_gnutls_cred_type (XPROCESS (proc), Qnil);
1392 #endif
1393
1394 #ifdef ADAPTIVE_READ_BUFFERING
1395 XPROCESS (proc)->adaptive_read_buffering
1396 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1397 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1398 #endif
1399
1400 /* Make the process marker point into the process buffer (if any). */
1401 if (BUFFERP (buffer))
1402 set_marker_both (XPROCESS (proc)->mark, buffer,
1403 BUF_ZV (XBUFFER (buffer)),
1404 BUF_ZV_BYTE (XBUFFER (buffer)));
1405
1406 {
1407 /* Decide coding systems for communicating with the process. Here
1408 we don't setup the structure coding_system nor pay attention to
1409 unibyte mode. They are done in create_process. */
1410
1411 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1412 Lisp_Object coding_systems = Qt;
1413 Lisp_Object val, *args2;
1414 struct gcpro gcpro1, gcpro2;
1415
1416 val = Vcoding_system_for_read;
1417 if (NILP (val))
1418 {
1419 args2 = alloca ((nargs + 1) * sizeof *args2);
1420 args2[0] = Qstart_process;
1421 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1422 GCPRO2 (proc, current_dir);
1423 if (!NILP (program))
1424 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1425 UNGCPRO;
1426 if (CONSP (coding_systems))
1427 val = XCAR (coding_systems);
1428 else if (CONSP (Vdefault_process_coding_system))
1429 val = XCAR (Vdefault_process_coding_system);
1430 }
1431 pset_decode_coding_system (XPROCESS (proc), val);
1432
1433 val = Vcoding_system_for_write;
1434 if (NILP (val))
1435 {
1436 if (EQ (coding_systems, Qt))
1437 {
1438 args2 = alloca ((nargs + 1) * sizeof *args2);
1439 args2[0] = Qstart_process;
1440 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1441 GCPRO2 (proc, current_dir);
1442 if (!NILP (program))
1443 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1444 UNGCPRO;
1445 }
1446 if (CONSP (coding_systems))
1447 val = XCDR (coding_systems);
1448 else if (CONSP (Vdefault_process_coding_system))
1449 val = XCDR (Vdefault_process_coding_system);
1450 }
1451 pset_encode_coding_system (XPROCESS (proc), val);
1452 /* Note: At this moment, the above coding system may leave
1453 text-conversion or eol-conversion unspecified. They will be
1454 decided after we read output from the process and decode it by
1455 some coding system, or just before we actually send a text to
1456 the process. */
1457 }
1458
1459
1460 pset_decoding_buf (XPROCESS (proc), empty_unibyte_string);
1461 XPROCESS (proc)->decoding_carryover = 0;
1462 pset_encoding_buf (XPROCESS (proc), empty_unibyte_string);
1463
1464 XPROCESS (proc)->inherit_coding_system_flag
1465 = !(NILP (buffer) || !inherit_process_coding_system);
1466
1467 if (!NILP (program))
1468 {
1469 /* If program file name is not absolute, search our path for it.
1470 Put the name we will really use in TEM. */
1471 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1472 && !(SCHARS (program) > 1
1473 && IS_DEVICE_SEP (SREF (program, 1))))
1474 {
1475 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1476
1477 tem = Qnil;
1478 GCPRO4 (name, program, buffer, current_dir);
1479 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1480 UNGCPRO;
1481 if (NILP (tem))
1482 report_file_error ("Searching for program", Fcons (program, Qnil));
1483 tem = Fexpand_file_name (tem, Qnil);
1484 }
1485 else
1486 {
1487 if (!NILP (Ffile_directory_p (program)))
1488 error ("Specified program for new process is a directory");
1489 tem = program;
1490 }
1491
1492 /* If program file name starts with /: for quoting a magic name,
1493 discard that. */
1494 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1495 && SREF (tem, 1) == ':')
1496 tem = Fsubstring (tem, make_number (2), Qnil);
1497
1498 {
1499 Lisp_Object arg_encoding = Qnil;
1500 struct gcpro gcpro1;
1501 GCPRO1 (tem);
1502
1503 /* Encode the file name and put it in NEW_ARGV.
1504 That's where the child will use it to execute the program. */
1505 tem = Fcons (ENCODE_FILE (tem), Qnil);
1506
1507 /* Here we encode arguments by the coding system used for sending
1508 data to the process. We don't support using different coding
1509 systems for encoding arguments and for encoding data sent to the
1510 process. */
1511
1512 for (i = 3; i < nargs; i++)
1513 {
1514 tem = Fcons (args[i], tem);
1515 CHECK_STRING (XCAR (tem));
1516 if (STRING_MULTIBYTE (XCAR (tem)))
1517 {
1518 if (NILP (arg_encoding))
1519 arg_encoding = (complement_process_encoding_system
1520 (XPROCESS (proc)->encode_coding_system));
1521 XSETCAR (tem,
1522 code_convert_string_norecord
1523 (XCAR (tem), arg_encoding, 1));
1524 }
1525 }
1526
1527 UNGCPRO;
1528 }
1529
1530 /* Now that everything is encoded we can collect the strings into
1531 NEW_ARGV. */
1532 new_argv = alloca ((nargs - 1) * sizeof *new_argv);
1533 new_argv[nargs - 2] = 0;
1534
1535 for (i = nargs - 2; i-- != 0; )
1536 {
1537 new_argv[i] = SDATA (XCAR (tem));
1538 tem = XCDR (tem);
1539 }
1540
1541 create_process (proc, (char **) new_argv, current_dir);
1542 }
1543 else
1544 create_pty (proc);
1545
1546 return unbind_to (count, proc);
1547 }
1548
1549 /* This function is the unwind_protect form for Fstart_process. If
1550 PROC doesn't have its pid set, then we know someone has signaled
1551 an error and the process wasn't started successfully, so we should
1552 remove it from the process list. */
1553 static Lisp_Object
1554 start_process_unwind (Lisp_Object proc)
1555 {
1556 if (!PROCESSP (proc))
1557 emacs_abort ();
1558
1559 /* Was PROC started successfully?
1560 -2 is used for a pty with no process, eg for gdb. */
1561 if (XPROCESS (proc)->pid <= 0 && XPROCESS (proc)->pid != -2)
1562 remove_process (proc);
1563
1564 return Qnil;
1565 }
1566
1567 static void
1568 create_process_1 (struct atimer *timer)
1569 {
1570 /* Nothing to do. */
1571 }
1572
1573
1574 static void
1575 create_process (Lisp_Object process, char **new_argv, Lisp_Object current_dir)
1576 {
1577 int inchannel, outchannel;
1578 pid_t pid;
1579 int sv[2];
1580 #ifndef WINDOWSNT
1581 int wait_child_setup[2];
1582 #endif
1583 sigset_t blocked;
1584 /* Use volatile to protect variables from being clobbered by vfork. */
1585 volatile int forkin, forkout;
1586 volatile int pty_flag = 0;
1587 volatile Lisp_Object lisp_pty_name = Qnil;
1588 volatile Lisp_Object encoded_current_dir;
1589
1590 inchannel = outchannel = -1;
1591
1592 #ifdef HAVE_PTYS
1593 if (!NILP (Vprocess_connection_type))
1594 outchannel = inchannel = allocate_pty ();
1595
1596 if (inchannel >= 0)
1597 {
1598 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1599 /* On most USG systems it does not work to open the pty's tty here,
1600 then close it and reopen it in the child. */
1601 /* Don't let this terminal become our controlling terminal
1602 (in case we don't have one). */
1603 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1604 if (forkin < 0)
1605 report_file_error ("Opening pty", Qnil);
1606 #else
1607 forkin = forkout = -1;
1608 #endif /* not USG, or USG_SUBTTY_WORKS */
1609 pty_flag = 1;
1610 lisp_pty_name = build_string (pty_name);
1611 }
1612 else
1613 #endif /* HAVE_PTYS */
1614 {
1615 int tem;
1616 tem = pipe (sv);
1617 if (tem < 0)
1618 report_file_error ("Creating pipe", Qnil);
1619 inchannel = sv[0];
1620 forkout = sv[1];
1621 tem = pipe (sv);
1622 if (tem < 0)
1623 {
1624 emacs_close (inchannel);
1625 emacs_close (forkout);
1626 report_file_error ("Creating pipe", Qnil);
1627 }
1628 outchannel = sv[1];
1629 forkin = sv[0];
1630 }
1631
1632 #ifndef WINDOWSNT
1633 {
1634 int tem;
1635
1636 tem = pipe (wait_child_setup);
1637 if (tem < 0)
1638 report_file_error ("Creating pipe", Qnil);
1639 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1640 if (tem >= 0)
1641 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1642 if (tem < 0)
1643 {
1644 emacs_close (wait_child_setup[0]);
1645 emacs_close (wait_child_setup[1]);
1646 report_file_error ("Setting file descriptor flags", Qnil);
1647 }
1648 }
1649 #endif
1650
1651 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1652 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1653
1654 /* Record this as an active process, with its channels.
1655 As a result, child_setup will close Emacs's side of the pipes. */
1656 chan_process[inchannel] = process;
1657 XPROCESS (process)->infd = inchannel;
1658 XPROCESS (process)->outfd = outchannel;
1659
1660 /* Previously we recorded the tty descriptor used in the subprocess.
1661 It was only used for getting the foreground tty process, so now
1662 we just reopen the device (see emacs_get_tty_pgrp) as this is
1663 more portable (see USG_SUBTTY_WORKS above). */
1664
1665 XPROCESS (process)->pty_flag = pty_flag;
1666 pset_status (XPROCESS (process), Qrun);
1667
1668 FD_SET (inchannel, &input_wait_mask);
1669 FD_SET (inchannel, &non_keyboard_wait_mask);
1670 if (inchannel > max_process_desc)
1671 max_process_desc = inchannel;
1672
1673 /* This may signal an error. */
1674 setup_process_coding_systems (process);
1675
1676 encoded_current_dir = ENCODE_FILE (current_dir);
1677
1678 block_input ();
1679
1680 /* Block SIGCHLD until we have a chance to store the new fork's
1681 pid in its process structure. */
1682 sigemptyset (&blocked);
1683 sigaddset (&blocked, SIGCHLD);
1684 pthread_sigmask (SIG_BLOCK, &blocked, 0);
1685
1686 #ifndef WINDOWSNT
1687 pid = vfork ();
1688 if (pid == 0)
1689 #endif /* not WINDOWSNT */
1690 {
1691 int xforkin = forkin;
1692 int xforkout = forkout;
1693
1694 /* Make the pty be the controlling terminal of the process. */
1695 #ifdef HAVE_PTYS
1696 /* First, disconnect its current controlling terminal. */
1697 /* We tried doing setsid only if pty_flag, but it caused
1698 process_set_signal to fail on SGI when using a pipe. */
1699 setsid ();
1700 /* Make the pty's terminal the controlling terminal. */
1701 if (pty_flag && xforkin >= 0)
1702 {
1703 #ifdef TIOCSCTTY
1704 /* We ignore the return value
1705 because faith@cs.unc.edu says that is necessary on Linux. */
1706 ioctl (xforkin, TIOCSCTTY, 0);
1707 #endif
1708 }
1709 #if defined (LDISC1)
1710 if (pty_flag && xforkin >= 0)
1711 {
1712 struct termios t;
1713 tcgetattr (xforkin, &t);
1714 t.c_lflag = LDISC1;
1715 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1716 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1717 }
1718 #else
1719 #if defined (NTTYDISC) && defined (TIOCSETD)
1720 if (pty_flag && xforkin >= 0)
1721 {
1722 /* Use new line discipline. */
1723 int ldisc = NTTYDISC;
1724 ioctl (xforkin, TIOCSETD, &ldisc);
1725 }
1726 #endif
1727 #endif
1728 #ifdef TIOCNOTTY
1729 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1730 can do TIOCSPGRP only to the process's controlling tty. */
1731 if (pty_flag)
1732 {
1733 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1734 I can't test it since I don't have 4.3. */
1735 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1736 if (j >= 0)
1737 {
1738 ioctl (j, TIOCNOTTY, 0);
1739 emacs_close (j);
1740 }
1741 }
1742 #endif /* TIOCNOTTY */
1743
1744 #if !defined (DONT_REOPEN_PTY)
1745 /*** There is a suggestion that this ought to be a
1746 conditional on TIOCSPGRP, or !defined TIOCSCTTY.
1747 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1748 that system does seem to need this code, even though
1749 both TIOCSCTTY is defined. */
1750 /* Now close the pty (if we had it open) and reopen it.
1751 This makes the pty the controlling terminal of the subprocess. */
1752 if (pty_flag)
1753 {
1754
1755 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1756 would work? */
1757 if (xforkin >= 0)
1758 emacs_close (xforkin);
1759 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1760
1761 if (xforkin < 0)
1762 {
1763 emacs_write (1, "Couldn't open the pty terminal ", 31);
1764 emacs_write (1, pty_name, strlen (pty_name));
1765 emacs_write (1, "\n", 1);
1766 _exit (1);
1767 }
1768
1769 }
1770 #endif /* not DONT_REOPEN_PTY */
1771
1772 #ifdef SETUP_SLAVE_PTY
1773 if (pty_flag)
1774 {
1775 SETUP_SLAVE_PTY;
1776 }
1777 #endif /* SETUP_SLAVE_PTY */
1778 #ifdef AIX
1779 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1780 Now reenable it in the child, so it will die when we want it to. */
1781 if (pty_flag)
1782 signal (SIGHUP, SIG_DFL);
1783 #endif
1784 #endif /* HAVE_PTYS */
1785
1786 signal (SIGINT, SIG_DFL);
1787 signal (SIGQUIT, SIG_DFL);
1788
1789 /* Emacs ignores SIGPIPE, but the child should not. */
1790 signal (SIGPIPE, SIG_DFL);
1791
1792 /* Stop blocking signals in the child. */
1793 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1794
1795 if (pty_flag)
1796 child_setup_tty (xforkout);
1797 #ifdef WINDOWSNT
1798 pid = child_setup (xforkin, xforkout, xforkout,
1799 new_argv, 1, encoded_current_dir);
1800 #else /* not WINDOWSNT */
1801 emacs_close (wait_child_setup[0]);
1802 child_setup (xforkin, xforkout, xforkout,
1803 new_argv, 1, encoded_current_dir);
1804 #endif /* not WINDOWSNT */
1805 }
1806
1807 /* Back in the parent process. */
1808
1809 XPROCESS (process)->pid = pid;
1810 if (0 <= pid)
1811 XPROCESS (process)->alive = 1;
1812
1813 /* Stop blocking signals in the parent. */
1814 pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
1815 unblock_input ();
1816
1817 if (pid < 0)
1818 {
1819 if (forkin >= 0)
1820 emacs_close (forkin);
1821 if (forkin != forkout && forkout >= 0)
1822 emacs_close (forkout);
1823 }
1824 else
1825 {
1826 /* vfork succeeded. */
1827
1828 #ifdef WINDOWSNT
1829 register_child (pid, inchannel);
1830 #endif /* WINDOWSNT */
1831
1832 /* If the subfork execv fails, and it exits,
1833 this close hangs. I don't know why.
1834 So have an interrupt jar it loose. */
1835 {
1836 struct atimer *timer;
1837 EMACS_TIME offset = make_emacs_time (1, 0);
1838
1839 stop_polling ();
1840 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
1841
1842 if (forkin >= 0)
1843 emacs_close (forkin);
1844
1845 cancel_atimer (timer);
1846 start_polling ();
1847 }
1848
1849 if (forkin != forkout && forkout >= 0)
1850 emacs_close (forkout);
1851
1852 pset_tty_name (XPROCESS (process), lisp_pty_name);
1853
1854 #ifndef WINDOWSNT
1855 /* Wait for child_setup to complete in case that vfork is
1856 actually defined as fork. The descriptor wait_child_setup[1]
1857 of a pipe is closed at the child side either by close-on-exec
1858 on successful execve or the _exit call in child_setup. */
1859 {
1860 char dummy;
1861
1862 emacs_close (wait_child_setup[1]);
1863 emacs_read (wait_child_setup[0], &dummy, 1);
1864 emacs_close (wait_child_setup[0]);
1865 }
1866 #endif
1867 }
1868
1869 /* Now generate the error if vfork failed. */
1870 if (pid < 0)
1871 report_file_error ("Doing vfork", Qnil);
1872 }
1873
1874 void
1875 create_pty (Lisp_Object process)
1876 {
1877 int inchannel, outchannel;
1878 int pty_flag = 0;
1879
1880 inchannel = outchannel = -1;
1881
1882 #ifdef HAVE_PTYS
1883 if (!NILP (Vprocess_connection_type))
1884 outchannel = inchannel = allocate_pty ();
1885
1886 if (inchannel >= 0)
1887 {
1888 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1889 /* On most USG systems it does not work to open the pty's tty here,
1890 then close it and reopen it in the child. */
1891 /* Don't let this terminal become our controlling terminal
1892 (in case we don't have one). */
1893 int forkout = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1894 if (forkout < 0)
1895 report_file_error ("Opening pty", Qnil);
1896 #if defined (DONT_REOPEN_PTY)
1897 /* In the case that vfork is defined as fork, the parent process
1898 (Emacs) may send some data before the child process completes
1899 tty options setup. So we setup tty before forking. */
1900 child_setup_tty (forkout);
1901 #endif /* DONT_REOPEN_PTY */
1902 #endif /* not USG, or USG_SUBTTY_WORKS */
1903 pty_flag = 1;
1904 }
1905 #endif /* HAVE_PTYS */
1906
1907 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1908 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1909
1910 /* Record this as an active process, with its channels.
1911 As a result, child_setup will close Emacs's side of the pipes. */
1912 chan_process[inchannel] = process;
1913 XPROCESS (process)->infd = inchannel;
1914 XPROCESS (process)->outfd = outchannel;
1915
1916 /* Previously we recorded the tty descriptor used in the subprocess.
1917 It was only used for getting the foreground tty process, so now
1918 we just reopen the device (see emacs_get_tty_pgrp) as this is
1919 more portable (see USG_SUBTTY_WORKS above). */
1920
1921 XPROCESS (process)->pty_flag = pty_flag;
1922 pset_status (XPROCESS (process), Qrun);
1923 setup_process_coding_systems (process);
1924
1925 FD_SET (inchannel, &input_wait_mask);
1926 FD_SET (inchannel, &non_keyboard_wait_mask);
1927 if (inchannel > max_process_desc)
1928 max_process_desc = inchannel;
1929
1930 XPROCESS (process)->pid = -2;
1931 #ifdef HAVE_PTYS
1932 if (pty_flag)
1933 pset_tty_name (XPROCESS (process), build_string (pty_name));
1934 else
1935 #endif
1936 pset_tty_name (XPROCESS (process), Qnil);
1937 }
1938
1939 \f
1940 /* Convert an internal struct sockaddr to a lisp object (vector or string).
1941 The address family of sa is not included in the result. */
1942
1943 static Lisp_Object
1944 conv_sockaddr_to_lisp (struct sockaddr *sa, int len)
1945 {
1946 Lisp_Object address;
1947 int i;
1948 unsigned char *cp;
1949 register struct Lisp_Vector *p;
1950
1951 /* Workaround for a bug in getsockname on BSD: Names bound to
1952 sockets in the UNIX domain are inaccessible; getsockname returns
1953 a zero length name. */
1954 if (len < offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family))
1955 return empty_unibyte_string;
1956
1957 switch (sa->sa_family)
1958 {
1959 case AF_INET:
1960 {
1961 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
1962 len = sizeof (sin->sin_addr) + 1;
1963 address = Fmake_vector (make_number (len), Qnil);
1964 p = XVECTOR (address);
1965 p->contents[--len] = make_number (ntohs (sin->sin_port));
1966 cp = (unsigned char *) &sin->sin_addr;
1967 break;
1968 }
1969 #ifdef AF_INET6
1970 case AF_INET6:
1971 {
1972 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
1973 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
1974 len = sizeof (sin6->sin6_addr)/2 + 1;
1975 address = Fmake_vector (make_number (len), Qnil);
1976 p = XVECTOR (address);
1977 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
1978 for (i = 0; i < len; i++)
1979 p->contents[i] = make_number (ntohs (ip6[i]));
1980 return address;
1981 }
1982 #endif
1983 #ifdef HAVE_LOCAL_SOCKETS
1984 case AF_LOCAL:
1985 {
1986 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
1987 for (i = 0; i < sizeof (sockun->sun_path); i++)
1988 if (sockun->sun_path[i] == 0)
1989 break;
1990 return make_unibyte_string (sockun->sun_path, i);
1991 }
1992 #endif
1993 default:
1994 len -= offsetof (struct sockaddr, sa_family) + sizeof (sa->sa_family);
1995 address = Fcons (make_number (sa->sa_family),
1996 Fmake_vector (make_number (len), Qnil));
1997 p = XVECTOR (XCDR (address));
1998 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
1999 break;
2000 }
2001
2002 i = 0;
2003 while (i < len)
2004 p->contents[i++] = make_number (*cp++);
2005
2006 return address;
2007 }
2008
2009
2010 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2011
2012 static int
2013 get_lisp_to_sockaddr_size (Lisp_Object address, int *familyp)
2014 {
2015 register struct Lisp_Vector *p;
2016
2017 if (VECTORP (address))
2018 {
2019 p = XVECTOR (address);
2020 if (p->header.size == 5)
2021 {
2022 *familyp = AF_INET;
2023 return sizeof (struct sockaddr_in);
2024 }
2025 #ifdef AF_INET6
2026 else if (p->header.size == 9)
2027 {
2028 *familyp = AF_INET6;
2029 return sizeof (struct sockaddr_in6);
2030 }
2031 #endif
2032 }
2033 #ifdef HAVE_LOCAL_SOCKETS
2034 else if (STRINGP (address))
2035 {
2036 *familyp = AF_LOCAL;
2037 return sizeof (struct sockaddr_un);
2038 }
2039 #endif
2040 else if (CONSP (address) && TYPE_RANGED_INTEGERP (int, XCAR (address))
2041 && VECTORP (XCDR (address)))
2042 {
2043 struct sockaddr *sa;
2044 *familyp = XINT (XCAR (address));
2045 p = XVECTOR (XCDR (address));
2046 return p->header.size + sizeof (sa->sa_family);
2047 }
2048 return 0;
2049 }
2050
2051 /* Convert an address object (vector or string) to an internal sockaddr.
2052
2053 The address format has been basically validated by
2054 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2055 it could have come from user data. So if FAMILY is not valid,
2056 we return after zeroing *SA. */
2057
2058 static void
2059 conv_lisp_to_sockaddr (int family, Lisp_Object address, struct sockaddr *sa, int len)
2060 {
2061 register struct Lisp_Vector *p;
2062 register unsigned char *cp = NULL;
2063 register int i;
2064 EMACS_INT hostport;
2065
2066 memset (sa, 0, len);
2067
2068 if (VECTORP (address))
2069 {
2070 p = XVECTOR (address);
2071 if (family == AF_INET)
2072 {
2073 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2074 len = sizeof (sin->sin_addr) + 1;
2075 hostport = XINT (p->contents[--len]);
2076 sin->sin_port = htons (hostport);
2077 cp = (unsigned char *)&sin->sin_addr;
2078 sa->sa_family = family;
2079 }
2080 #ifdef AF_INET6
2081 else if (family == AF_INET6)
2082 {
2083 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2084 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2085 len = sizeof (sin6->sin6_addr) + 1;
2086 hostport = XINT (p->contents[--len]);
2087 sin6->sin6_port = htons (hostport);
2088 for (i = 0; i < len; i++)
2089 if (INTEGERP (p->contents[i]))
2090 {
2091 int j = XFASTINT (p->contents[i]) & 0xffff;
2092 ip6[i] = ntohs (j);
2093 }
2094 sa->sa_family = family;
2095 return;
2096 }
2097 #endif
2098 else
2099 return;
2100 }
2101 else if (STRINGP (address))
2102 {
2103 #ifdef HAVE_LOCAL_SOCKETS
2104 if (family == AF_LOCAL)
2105 {
2106 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2107 cp = SDATA (address);
2108 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2109 sockun->sun_path[i] = *cp++;
2110 sa->sa_family = family;
2111 }
2112 #endif
2113 return;
2114 }
2115 else
2116 {
2117 p = XVECTOR (XCDR (address));
2118 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2119 }
2120
2121 for (i = 0; i < len; i++)
2122 if (INTEGERP (p->contents[i]))
2123 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2124 }
2125
2126 #ifdef DATAGRAM_SOCKETS
2127 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2128 1, 1, 0,
2129 doc: /* Get the current datagram address associated with PROCESS. */)
2130 (Lisp_Object process)
2131 {
2132 int channel;
2133
2134 CHECK_PROCESS (process);
2135
2136 if (!DATAGRAM_CONN_P (process))
2137 return Qnil;
2138
2139 channel = XPROCESS (process)->infd;
2140 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2141 datagram_address[channel].len);
2142 }
2143
2144 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2145 2, 2, 0,
2146 doc: /* Set the datagram address for PROCESS to ADDRESS.
2147 Returns nil upon error setting address, ADDRESS otherwise. */)
2148 (Lisp_Object process, Lisp_Object address)
2149 {
2150 int channel;
2151 int family, len;
2152
2153 CHECK_PROCESS (process);
2154
2155 if (!DATAGRAM_CONN_P (process))
2156 return Qnil;
2157
2158 channel = XPROCESS (process)->infd;
2159
2160 len = get_lisp_to_sockaddr_size (address, &family);
2161 if (datagram_address[channel].len != len)
2162 return Qnil;
2163 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2164 return address;
2165 }
2166 #endif
2167 \f
2168
2169 static const struct socket_options {
2170 /* The name of this option. Should be lowercase version of option
2171 name without SO_ prefix. */
2172 const char *name;
2173 /* Option level SOL_... */
2174 int optlevel;
2175 /* Option number SO_... */
2176 int optnum;
2177 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2178 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2179 } socket_options[] =
2180 {
2181 #ifdef SO_BINDTODEVICE
2182 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2183 #endif
2184 #ifdef SO_BROADCAST
2185 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2186 #endif
2187 #ifdef SO_DONTROUTE
2188 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2189 #endif
2190 #ifdef SO_KEEPALIVE
2191 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2192 #endif
2193 #ifdef SO_LINGER
2194 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2195 #endif
2196 #ifdef SO_OOBINLINE
2197 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2198 #endif
2199 #ifdef SO_PRIORITY
2200 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2201 #endif
2202 #ifdef SO_REUSEADDR
2203 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2204 #endif
2205 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2206 };
2207
2208 /* Set option OPT to value VAL on socket S.
2209
2210 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2211 Signals an error if setting a known option fails.
2212 */
2213
2214 static int
2215 set_socket_option (int s, Lisp_Object opt, Lisp_Object val)
2216 {
2217 char *name;
2218 const struct socket_options *sopt;
2219 int ret = 0;
2220
2221 CHECK_SYMBOL (opt);
2222
2223 name = SSDATA (SYMBOL_NAME (opt));
2224 for (sopt = socket_options; sopt->name; sopt++)
2225 if (strcmp (name, sopt->name) == 0)
2226 break;
2227
2228 switch (sopt->opttype)
2229 {
2230 case SOPT_BOOL:
2231 {
2232 int optval;
2233 optval = NILP (val) ? 0 : 1;
2234 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2235 &optval, sizeof (optval));
2236 break;
2237 }
2238
2239 case SOPT_INT:
2240 {
2241 int optval;
2242 if (TYPE_RANGED_INTEGERP (int, val))
2243 optval = XINT (val);
2244 else
2245 error ("Bad option value for %s", name);
2246 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2247 &optval, sizeof (optval));
2248 break;
2249 }
2250
2251 #ifdef SO_BINDTODEVICE
2252 case SOPT_IFNAME:
2253 {
2254 char devname[IFNAMSIZ+1];
2255
2256 /* This is broken, at least in the Linux 2.4 kernel.
2257 To unbind, the arg must be a zero integer, not the empty string.
2258 This should work on all systems. KFS. 2003-09-23. */
2259 memset (devname, 0, sizeof devname);
2260 if (STRINGP (val))
2261 {
2262 char *arg = SSDATA (val);
2263 int len = min (strlen (arg), IFNAMSIZ);
2264 memcpy (devname, arg, len);
2265 }
2266 else if (!NILP (val))
2267 error ("Bad option value for %s", name);
2268 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2269 devname, IFNAMSIZ);
2270 break;
2271 }
2272 #endif
2273
2274 #ifdef SO_LINGER
2275 case SOPT_LINGER:
2276 {
2277 struct linger linger;
2278
2279 linger.l_onoff = 1;
2280 linger.l_linger = 0;
2281 if (TYPE_RANGED_INTEGERP (int, val))
2282 linger.l_linger = XINT (val);
2283 else
2284 linger.l_onoff = NILP (val) ? 0 : 1;
2285 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2286 &linger, sizeof (linger));
2287 break;
2288 }
2289 #endif
2290
2291 default:
2292 return 0;
2293 }
2294
2295 if (ret < 0)
2296 report_file_error ("Cannot set network option",
2297 Fcons (opt, Fcons (val, Qnil)));
2298 return (1 << sopt->optbit);
2299 }
2300
2301
2302 DEFUN ("set-network-process-option",
2303 Fset_network_process_option, Sset_network_process_option,
2304 3, 4, 0,
2305 doc: /* For network process PROCESS set option OPTION to value VALUE.
2306 See `make-network-process' for a list of options and values.
2307 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2308 OPTION is not a supported option, return nil instead; otherwise return t. */)
2309 (Lisp_Object process, Lisp_Object option, Lisp_Object value, Lisp_Object no_error)
2310 {
2311 int s;
2312 struct Lisp_Process *p;
2313
2314 CHECK_PROCESS (process);
2315 p = XPROCESS (process);
2316 if (!NETCONN1_P (p))
2317 error ("Process is not a network process");
2318
2319 s = p->infd;
2320 if (s < 0)
2321 error ("Process is not running");
2322
2323 if (set_socket_option (s, option, value))
2324 {
2325 pset_childp (p, Fplist_put (p->childp, option, value));
2326 return Qt;
2327 }
2328
2329 if (NILP (no_error))
2330 error ("Unknown or unsupported option");
2331
2332 return Qnil;
2333 }
2334
2335 \f
2336 DEFUN ("serial-process-configure",
2337 Fserial_process_configure,
2338 Sserial_process_configure,
2339 0, MANY, 0,
2340 doc: /* Configure speed, bytesize, etc. of a serial process.
2341
2342 Arguments are specified as keyword/argument pairs. Attributes that
2343 are not given are re-initialized from the process's current
2344 configuration (available via the function `process-contact') or set to
2345 reasonable default values. The following arguments are defined:
2346
2347 :process PROCESS
2348 :name NAME
2349 :buffer BUFFER
2350 :port PORT
2351 -- Any of these arguments can be given to identify the process that is
2352 to be configured. If none of these arguments is given, the current
2353 buffer's process is used.
2354
2355 :speed SPEED -- SPEED is the speed of the serial port in bits per
2356 second, also called baud rate. Any value can be given for SPEED, but
2357 most serial ports work only at a few defined values between 1200 and
2358 115200, with 9600 being the most common value. If SPEED is nil, the
2359 serial port is not configured any further, i.e., all other arguments
2360 are ignored. This may be useful for special serial ports such as
2361 Bluetooth-to-serial converters which can only be configured through AT
2362 commands. A value of nil for SPEED can be used only when passed
2363 through `make-serial-process' or `serial-term'.
2364
2365 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2366 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2367
2368 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2369 `odd' (use odd parity), or the symbol `even' (use even parity). If
2370 PARITY is not given, no parity is used.
2371
2372 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2373 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2374 is not given or nil, 1 stopbit is used.
2375
2376 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2377 flowcontrol to be used, which is either nil (don't use flowcontrol),
2378 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2379 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2380 flowcontrol is used.
2381
2382 `serial-process-configure' is called by `make-serial-process' for the
2383 initial configuration of the serial port.
2384
2385 Examples:
2386
2387 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2388
2389 \(serial-process-configure
2390 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2391
2392 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2393
2394 usage: (serial-process-configure &rest ARGS) */)
2395 (ptrdiff_t nargs, Lisp_Object *args)
2396 {
2397 struct Lisp_Process *p;
2398 Lisp_Object contact = Qnil;
2399 Lisp_Object proc = Qnil;
2400 struct gcpro gcpro1;
2401
2402 contact = Flist (nargs, args);
2403 GCPRO1 (contact);
2404
2405 proc = Fplist_get (contact, QCprocess);
2406 if (NILP (proc))
2407 proc = Fplist_get (contact, QCname);
2408 if (NILP (proc))
2409 proc = Fplist_get (contact, QCbuffer);
2410 if (NILP (proc))
2411 proc = Fplist_get (contact, QCport);
2412 proc = get_process (proc);
2413 p = XPROCESS (proc);
2414 if (!EQ (p->type, Qserial))
2415 error ("Not a serial process");
2416
2417 if (NILP (Fplist_get (p->childp, QCspeed)))
2418 {
2419 UNGCPRO;
2420 return Qnil;
2421 }
2422
2423 serial_configure (p, contact);
2424
2425 UNGCPRO;
2426 return Qnil;
2427 }
2428
2429 /* Used by make-serial-process to recover from errors. */
2430 static Lisp_Object
2431 make_serial_process_unwind (Lisp_Object proc)
2432 {
2433 if (!PROCESSP (proc))
2434 emacs_abort ();
2435 remove_process (proc);
2436 return Qnil;
2437 }
2438
2439 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2440 0, MANY, 0,
2441 doc: /* Create and return a serial port process.
2442
2443 In Emacs, serial port connections are represented by process objects,
2444 so input and output work as for subprocesses, and `delete-process'
2445 closes a serial port connection. However, a serial process has no
2446 process id, it cannot be signaled, and the status codes are different
2447 from normal processes.
2448
2449 `make-serial-process' creates a process and a buffer, on which you
2450 probably want to use `process-send-string'. Try \\[serial-term] for
2451 an interactive terminal. See below for examples.
2452
2453 Arguments are specified as keyword/argument pairs. The following
2454 arguments are defined:
2455
2456 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2457 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2458 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2459 the backslashes in strings).
2460
2461 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2462 which this function calls.
2463
2464 :name NAME -- NAME is the name of the process. If NAME is not given,
2465 the value of PORT is used.
2466
2467 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2468 with the process. Process output goes at the end of that buffer,
2469 unless you specify an output stream or filter function to handle the
2470 output. If BUFFER is not given, the value of NAME is used.
2471
2472 :coding CODING -- If CODING is a symbol, it specifies the coding
2473 system used for both reading and writing for this process. If CODING
2474 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2475 ENCODING is used for writing.
2476
2477 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2478 the process is running. If BOOL is not given, query before exiting.
2479
2480 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2481 In the stopped state, a serial process does not accept incoming data,
2482 but you can send outgoing data. The stopped state is cleared by
2483 `continue-process' and set by `stop-process'.
2484
2485 :filter FILTER -- Install FILTER as the process filter.
2486
2487 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2488
2489 :plist PLIST -- Install PLIST as the initial plist of the process.
2490
2491 :bytesize
2492 :parity
2493 :stopbits
2494 :flowcontrol
2495 -- This function calls `serial-process-configure' to handle these
2496 arguments.
2497
2498 The original argument list, possibly modified by later configuration,
2499 is available via the function `process-contact'.
2500
2501 Examples:
2502
2503 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2504
2505 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2506
2507 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2508
2509 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2510
2511 usage: (make-serial-process &rest ARGS) */)
2512 (ptrdiff_t nargs, Lisp_Object *args)
2513 {
2514 int fd = -1;
2515 Lisp_Object proc, contact, port;
2516 struct Lisp_Process *p;
2517 struct gcpro gcpro1;
2518 Lisp_Object name, buffer;
2519 Lisp_Object tem, val;
2520 ptrdiff_t specpdl_count = -1;
2521
2522 if (nargs == 0)
2523 return Qnil;
2524
2525 contact = Flist (nargs, args);
2526 GCPRO1 (contact);
2527
2528 port = Fplist_get (contact, QCport);
2529 if (NILP (port))
2530 error ("No port specified");
2531 CHECK_STRING (port);
2532
2533 if (NILP (Fplist_member (contact, QCspeed)))
2534 error (":speed not specified");
2535 if (!NILP (Fplist_get (contact, QCspeed)))
2536 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2537
2538 name = Fplist_get (contact, QCname);
2539 if (NILP (name))
2540 name = port;
2541 CHECK_STRING (name);
2542 proc = make_process (name);
2543 specpdl_count = SPECPDL_INDEX ();
2544 record_unwind_protect (make_serial_process_unwind, proc);
2545 p = XPROCESS (proc);
2546
2547 fd = serial_open (SSDATA (port));
2548 p->infd = fd;
2549 p->outfd = fd;
2550 if (fd > max_process_desc)
2551 max_process_desc = fd;
2552 chan_process[fd] = proc;
2553
2554 buffer = Fplist_get (contact, QCbuffer);
2555 if (NILP (buffer))
2556 buffer = name;
2557 buffer = Fget_buffer_create (buffer);
2558 pset_buffer (p, buffer);
2559
2560 pset_childp (p, contact);
2561 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
2562 pset_type (p, Qserial);
2563 pset_sentinel (p, Fplist_get (contact, QCsentinel));
2564 pset_filter (p, Fplist_get (contact, QCfilter));
2565 pset_log (p, Qnil);
2566 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2567 p->kill_without_query = 1;
2568 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2569 pset_command (p, Qt);
2570 p->pty_flag = 0;
2571
2572 if (!EQ (p->command, Qt))
2573 {
2574 FD_SET (fd, &input_wait_mask);
2575 FD_SET (fd, &non_keyboard_wait_mask);
2576 }
2577
2578 if (BUFFERP (buffer))
2579 {
2580 set_marker_both (p->mark, buffer,
2581 BUF_ZV (XBUFFER (buffer)),
2582 BUF_ZV_BYTE (XBUFFER (buffer)));
2583 }
2584
2585 tem = Fplist_member (contact, QCcoding);
2586 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2587 tem = Qnil;
2588
2589 val = Qnil;
2590 if (!NILP (tem))
2591 {
2592 val = XCAR (XCDR (tem));
2593 if (CONSP (val))
2594 val = XCAR (val);
2595 }
2596 else if (!NILP (Vcoding_system_for_read))
2597 val = Vcoding_system_for_read;
2598 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2599 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2600 val = Qnil;
2601 pset_decode_coding_system (p, val);
2602
2603 val = Qnil;
2604 if (!NILP (tem))
2605 {
2606 val = XCAR (XCDR (tem));
2607 if (CONSP (val))
2608 val = XCDR (val);
2609 }
2610 else if (!NILP (Vcoding_system_for_write))
2611 val = Vcoding_system_for_write;
2612 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
2613 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
2614 val = Qnil;
2615 pset_encode_coding_system (p, val);
2616
2617 setup_process_coding_systems (proc);
2618 pset_decoding_buf (p, empty_unibyte_string);
2619 p->decoding_carryover = 0;
2620 pset_encoding_buf (p, empty_unibyte_string);
2621 p->inherit_coding_system_flag
2622 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2623
2624 Fserial_process_configure (nargs, args);
2625
2626 specpdl_ptr = specpdl + specpdl_count;
2627
2628 UNGCPRO;
2629 return proc;
2630 }
2631
2632 /* Create a network stream/datagram client/server process. Treated
2633 exactly like a normal process when reading and writing. Primary
2634 differences are in status display and process deletion. A network
2635 connection has no PID; you cannot signal it. All you can do is
2636 stop/continue it and deactivate/close it via delete-process */
2637
2638 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2639 0, MANY, 0,
2640 doc: /* Create and return a network server or client process.
2641
2642 In Emacs, network connections are represented by process objects, so
2643 input and output work as for subprocesses and `delete-process' closes
2644 a network connection. However, a network process has no process id,
2645 it cannot be signaled, and the status codes are different from normal
2646 processes.
2647
2648 Arguments are specified as keyword/argument pairs. The following
2649 arguments are defined:
2650
2651 :name NAME -- NAME is name for process. It is modified if necessary
2652 to make it unique.
2653
2654 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2655 with the process. Process output goes at end of that buffer, unless
2656 you specify an output stream or filter function to handle the output.
2657 BUFFER may be also nil, meaning that this process is not associated
2658 with any buffer.
2659
2660 :host HOST -- HOST is name of the host to connect to, or its IP
2661 address. The symbol `local' specifies the local host. If specified
2662 for a server process, it must be a valid name or address for the local
2663 host, and only clients connecting to that address will be accepted.
2664
2665 :service SERVICE -- SERVICE is name of the service desired, or an
2666 integer specifying a port number to connect to. If SERVICE is t,
2667 a random port number is selected for the server. (If Emacs was
2668 compiled with getaddrinfo, a port number can also be specified as a
2669 string, e.g. "80", as well as an integer. This is not portable.)
2670
2671 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2672 stream type connection, `datagram' creates a datagram type connection,
2673 `seqpacket' creates a reliable datagram connection.
2674
2675 :family FAMILY -- FAMILY is the address (and protocol) family for the
2676 service specified by HOST and SERVICE. The default (nil) is to use
2677 whatever address family (IPv4 or IPv6) that is defined for the host
2678 and port number specified by HOST and SERVICE. Other address families
2679 supported are:
2680 local -- for a local (i.e. UNIX) address specified by SERVICE.
2681 ipv4 -- use IPv4 address family only.
2682 ipv6 -- use IPv6 address family only.
2683
2684 :local ADDRESS -- ADDRESS is the local address used for the connection.
2685 This parameter is ignored when opening a client process. When specified
2686 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2687
2688 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2689 connection. This parameter is ignored when opening a stream server
2690 process. For a datagram server process, it specifies the initial
2691 setting of the remote datagram address. When specified for a client
2692 process, the FAMILY, HOST, and SERVICE args are ignored.
2693
2694 The format of ADDRESS depends on the address family:
2695 - An IPv4 address is represented as an vector of integers [A B C D P]
2696 corresponding to numeric IP address A.B.C.D and port number P.
2697 - A local address is represented as a string with the address in the
2698 local address space.
2699 - An "unsupported family" address is represented by a cons (F . AV)
2700 where F is the family number and AV is a vector containing the socket
2701 address data with one element per address data byte. Do not rely on
2702 this format in portable code, as it may depend on implementation
2703 defined constants, data sizes, and data structure alignment.
2704
2705 :coding CODING -- If CODING is a symbol, it specifies the coding
2706 system used for both reading and writing for this process. If CODING
2707 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2708 ENCODING is used for writing.
2709
2710 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2711 return without waiting for the connection to complete; instead, the
2712 sentinel function will be called with second arg matching "open" (if
2713 successful) or "failed" when the connect completes. Default is to use
2714 a blocking connect (i.e. wait) for stream type connections.
2715
2716 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2717 running when Emacs is exited.
2718
2719 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2720 In the stopped state, a server process does not accept new
2721 connections, and a client process does not handle incoming traffic.
2722 The stopped state is cleared by `continue-process' and set by
2723 `stop-process'.
2724
2725 :filter FILTER -- Install FILTER as the process filter.
2726
2727 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
2728 process filter are multibyte, otherwise they are unibyte.
2729 If this keyword is not specified, the strings are multibyte if
2730 the default value of `enable-multibyte-characters' is non-nil.
2731
2732 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2733
2734 :log LOG -- Install LOG as the server process log function. This
2735 function is called when the server accepts a network connection from a
2736 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2737 is the server process, CLIENT is the new process for the connection,
2738 and MESSAGE is a string.
2739
2740 :plist PLIST -- Install PLIST as the new process' initial plist.
2741
2742 :server QLEN -- if QLEN is non-nil, create a server process for the
2743 specified FAMILY, SERVICE, and connection type (stream or datagram).
2744 If QLEN is an integer, it is used as the max. length of the server's
2745 pending connection queue (also known as the backlog); the default
2746 queue length is 5. Default is to create a client process.
2747
2748 The following network options can be specified for this connection:
2749
2750 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
2751 :dontroute BOOL -- Only send to directly connected hosts.
2752 :keepalive BOOL -- Send keep-alive messages on network stream.
2753 :linger BOOL or TIMEOUT -- Send queued messages before closing.
2754 :oobinline BOOL -- Place out-of-band data in receive data stream.
2755 :priority INT -- Set protocol defined priority for sent packets.
2756 :reuseaddr BOOL -- Allow reusing a recently used local address
2757 (this is allowed by default for a server process).
2758 :bindtodevice NAME -- bind to interface NAME. Using this may require
2759 special privileges on some systems.
2760
2761 Consult the relevant system programmer's manual pages for more
2762 information on using these options.
2763
2764
2765 A server process will listen for and accept connections from clients.
2766 When a client connection is accepted, a new network process is created
2767 for the connection with the following parameters:
2768
2769 - The client's process name is constructed by concatenating the server
2770 process' NAME and a client identification string.
2771 - If the FILTER argument is non-nil, the client process will not get a
2772 separate process buffer; otherwise, the client's process buffer is a newly
2773 created buffer named after the server process' BUFFER name or process
2774 NAME concatenated with the client identification string.
2775 - The connection type and the process filter and sentinel parameters are
2776 inherited from the server process' TYPE, FILTER and SENTINEL.
2777 - The client process' contact info is set according to the client's
2778 addressing information (typically an IP address and a port number).
2779 - The client process' plist is initialized from the server's plist.
2780
2781 Notice that the FILTER and SENTINEL args are never used directly by
2782 the server process. Also, the BUFFER argument is not used directly by
2783 the server process, but via the optional :log function, accepted (and
2784 failed) connections may be logged in the server process' buffer.
2785
2786 The original argument list, modified with the actual connection
2787 information, is available via the `process-contact' function.
2788
2789 usage: (make-network-process &rest ARGS) */)
2790 (ptrdiff_t nargs, Lisp_Object *args)
2791 {
2792 Lisp_Object proc;
2793 Lisp_Object contact;
2794 struct Lisp_Process *p;
2795 #ifdef HAVE_GETADDRINFO
2796 struct addrinfo ai, *res, *lres;
2797 struct addrinfo hints;
2798 const char *portstring;
2799 char portbuf[128];
2800 #else /* HAVE_GETADDRINFO */
2801 struct _emacs_addrinfo
2802 {
2803 int ai_family;
2804 int ai_socktype;
2805 int ai_protocol;
2806 int ai_addrlen;
2807 struct sockaddr *ai_addr;
2808 struct _emacs_addrinfo *ai_next;
2809 } ai, *res, *lres;
2810 #endif /* HAVE_GETADDRINFO */
2811 struct sockaddr_in address_in;
2812 #ifdef HAVE_LOCAL_SOCKETS
2813 struct sockaddr_un address_un;
2814 #endif
2815 int port;
2816 int ret = 0;
2817 int xerrno = 0;
2818 int s = -1, outch, inch;
2819 struct gcpro gcpro1;
2820 ptrdiff_t count = SPECPDL_INDEX ();
2821 ptrdiff_t count1;
2822 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2823 Lisp_Object tem;
2824 Lisp_Object name, buffer, host, service, address;
2825 Lisp_Object filter, sentinel;
2826 int is_non_blocking_client = 0;
2827 int is_server = 0, backlog = 5;
2828 int socktype;
2829 int family = -1;
2830
2831 if (nargs == 0)
2832 return Qnil;
2833
2834 /* Save arguments for process-contact and clone-process. */
2835 contact = Flist (nargs, args);
2836 GCPRO1 (contact);
2837
2838 #ifdef WINDOWSNT
2839 /* Ensure socket support is loaded if available. */
2840 init_winsock (TRUE);
2841 #endif
2842
2843 /* :type TYPE (nil: stream, datagram */
2844 tem = Fplist_get (contact, QCtype);
2845 if (NILP (tem))
2846 socktype = SOCK_STREAM;
2847 #ifdef DATAGRAM_SOCKETS
2848 else if (EQ (tem, Qdatagram))
2849 socktype = SOCK_DGRAM;
2850 #endif
2851 #ifdef HAVE_SEQPACKET
2852 else if (EQ (tem, Qseqpacket))
2853 socktype = SOCK_SEQPACKET;
2854 #endif
2855 else
2856 error ("Unsupported connection type");
2857
2858 /* :server BOOL */
2859 tem = Fplist_get (contact, QCserver);
2860 if (!NILP (tem))
2861 {
2862 /* Don't support network sockets when non-blocking mode is
2863 not available, since a blocked Emacs is not useful. */
2864 is_server = 1;
2865 if (TYPE_RANGED_INTEGERP (int, tem))
2866 backlog = XINT (tem);
2867 }
2868
2869 /* Make QCaddress an alias for :local (server) or :remote (client). */
2870 QCaddress = is_server ? QClocal : QCremote;
2871
2872 /* :nowait BOOL */
2873 if (!is_server && socktype != SOCK_DGRAM
2874 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2875 {
2876 #ifndef NON_BLOCKING_CONNECT
2877 error ("Non-blocking connect not supported");
2878 #else
2879 is_non_blocking_client = 1;
2880 #endif
2881 }
2882
2883 name = Fplist_get (contact, QCname);
2884 buffer = Fplist_get (contact, QCbuffer);
2885 filter = Fplist_get (contact, QCfilter);
2886 sentinel = Fplist_get (contact, QCsentinel);
2887
2888 CHECK_STRING (name);
2889
2890 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2891 ai.ai_socktype = socktype;
2892 ai.ai_protocol = 0;
2893 ai.ai_next = NULL;
2894 res = &ai;
2895
2896 /* :local ADDRESS or :remote ADDRESS */
2897 address = Fplist_get (contact, QCaddress);
2898 if (!NILP (address))
2899 {
2900 host = service = Qnil;
2901
2902 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2903 error ("Malformed :address");
2904 ai.ai_family = family;
2905 ai.ai_addr = alloca (ai.ai_addrlen);
2906 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2907 goto open_socket;
2908 }
2909
2910 /* :family FAMILY -- nil (for Inet), local, or integer. */
2911 tem = Fplist_get (contact, QCfamily);
2912 if (NILP (tem))
2913 {
2914 #if defined (HAVE_GETADDRINFO) && defined (AF_INET6)
2915 family = AF_UNSPEC;
2916 #else
2917 family = AF_INET;
2918 #endif
2919 }
2920 #ifdef HAVE_LOCAL_SOCKETS
2921 else if (EQ (tem, Qlocal))
2922 family = AF_LOCAL;
2923 #endif
2924 #ifdef AF_INET6
2925 else if (EQ (tem, Qipv6))
2926 family = AF_INET6;
2927 #endif
2928 else if (EQ (tem, Qipv4))
2929 family = AF_INET;
2930 else if (TYPE_RANGED_INTEGERP (int, tem))
2931 family = XINT (tem);
2932 else
2933 error ("Unknown address family");
2934
2935 ai.ai_family = family;
2936
2937 /* :service SERVICE -- string, integer (port number), or t (random port). */
2938 service = Fplist_get (contact, QCservice);
2939
2940 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2941 host = Fplist_get (contact, QChost);
2942 if (!NILP (host))
2943 {
2944 if (EQ (host, Qlocal))
2945 /* Depending on setup, "localhost" may map to different IPv4 and/or
2946 IPv6 addresses, so it's better to be explicit. (Bug#6781) */
2947 host = build_string ("127.0.0.1");
2948 CHECK_STRING (host);
2949 }
2950
2951 #ifdef HAVE_LOCAL_SOCKETS
2952 if (family == AF_LOCAL)
2953 {
2954 if (!NILP (host))
2955 {
2956 message (":family local ignores the :host \"%s\" property",
2957 SDATA (host));
2958 contact = Fplist_put (contact, QChost, Qnil);
2959 host = Qnil;
2960 }
2961 CHECK_STRING (service);
2962 memset (&address_un, 0, sizeof address_un);
2963 address_un.sun_family = AF_LOCAL;
2964 if (sizeof address_un.sun_path <= SBYTES (service))
2965 error ("Service name too long");
2966 strcpy (address_un.sun_path, SSDATA (service));
2967 ai.ai_addr = (struct sockaddr *) &address_un;
2968 ai.ai_addrlen = sizeof address_un;
2969 goto open_socket;
2970 }
2971 #endif
2972
2973 /* Slow down polling to every ten seconds.
2974 Some kernels have a bug which causes retrying connect to fail
2975 after a connect. Polling can interfere with gethostbyname too. */
2976 #ifdef POLL_FOR_INPUT
2977 if (socktype != SOCK_DGRAM)
2978 {
2979 record_unwind_protect (unwind_stop_other_atimers, Qnil);
2980 bind_polling_period (10);
2981 }
2982 #endif
2983
2984 #ifdef HAVE_GETADDRINFO
2985 /* If we have a host, use getaddrinfo to resolve both host and service.
2986 Otherwise, use getservbyname to lookup the service. */
2987 if (!NILP (host))
2988 {
2989
2990 /* SERVICE can either be a string or int.
2991 Convert to a C string for later use by getaddrinfo. */
2992 if (EQ (service, Qt))
2993 portstring = "0";
2994 else if (INTEGERP (service))
2995 {
2996 sprintf (portbuf, "%"pI"d", XINT (service));
2997 portstring = portbuf;
2998 }
2999 else
3000 {
3001 CHECK_STRING (service);
3002 portstring = SSDATA (service);
3003 }
3004
3005 immediate_quit = 1;
3006 QUIT;
3007 memset (&hints, 0, sizeof (hints));
3008 hints.ai_flags = 0;
3009 hints.ai_family = family;
3010 hints.ai_socktype = socktype;
3011 hints.ai_protocol = 0;
3012
3013 #ifdef HAVE_RES_INIT
3014 res_init ();
3015 #endif
3016
3017 ret = getaddrinfo (SSDATA (host), portstring, &hints, &res);
3018 if (ret)
3019 #ifdef HAVE_GAI_STRERROR
3020 error ("%s/%s %s", SSDATA (host), portstring, gai_strerror (ret));
3021 #else
3022 error ("%s/%s getaddrinfo error %d", SSDATA (host), portstring, ret);
3023 #endif
3024 immediate_quit = 0;
3025
3026 goto open_socket;
3027 }
3028 #endif /* HAVE_GETADDRINFO */
3029
3030 /* We end up here if getaddrinfo is not defined, or in case no hostname
3031 has been specified (e.g. for a local server process). */
3032
3033 if (EQ (service, Qt))
3034 port = 0;
3035 else if (INTEGERP (service))
3036 port = htons ((unsigned short) XINT (service));
3037 else
3038 {
3039 struct servent *svc_info;
3040 CHECK_STRING (service);
3041 svc_info = getservbyname (SSDATA (service),
3042 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3043 if (svc_info == 0)
3044 error ("Unknown service: %s", SDATA (service));
3045 port = svc_info->s_port;
3046 }
3047
3048 memset (&address_in, 0, sizeof address_in);
3049 address_in.sin_family = family;
3050 address_in.sin_addr.s_addr = INADDR_ANY;
3051 address_in.sin_port = port;
3052
3053 #ifndef HAVE_GETADDRINFO
3054 if (!NILP (host))
3055 {
3056 struct hostent *host_info_ptr;
3057
3058 /* gethostbyname may fail with TRY_AGAIN, but we don't honor that,
3059 as it may `hang' Emacs for a very long time. */
3060 immediate_quit = 1;
3061 QUIT;
3062
3063 #ifdef HAVE_RES_INIT
3064 res_init ();
3065 #endif
3066
3067 host_info_ptr = gethostbyname (SDATA (host));
3068 immediate_quit = 0;
3069
3070 if (host_info_ptr)
3071 {
3072 memcpy (&address_in.sin_addr, host_info_ptr->h_addr,
3073 host_info_ptr->h_length);
3074 family = host_info_ptr->h_addrtype;
3075 address_in.sin_family = family;
3076 }
3077 else
3078 /* Attempt to interpret host as numeric inet address */
3079 {
3080 unsigned long numeric_addr;
3081 numeric_addr = inet_addr (SSDATA (host));
3082 if (numeric_addr == -1)
3083 error ("Unknown host \"%s\"", SDATA (host));
3084
3085 memcpy (&address_in.sin_addr, &numeric_addr,
3086 sizeof (address_in.sin_addr));
3087 }
3088
3089 }
3090 #endif /* not HAVE_GETADDRINFO */
3091
3092 ai.ai_family = family;
3093 ai.ai_addr = (struct sockaddr *) &address_in;
3094 ai.ai_addrlen = sizeof address_in;
3095
3096 open_socket:
3097
3098 /* Do this in case we never enter the for-loop below. */
3099 count1 = SPECPDL_INDEX ();
3100 s = -1;
3101
3102 for (lres = res; lres; lres = lres->ai_next)
3103 {
3104 ptrdiff_t optn;
3105 int optbits;
3106
3107 #ifdef WINDOWSNT
3108 retry_connect:
3109 #endif
3110
3111 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3112 if (s < 0)
3113 {
3114 xerrno = errno;
3115 continue;
3116 }
3117
3118 #ifdef DATAGRAM_SOCKETS
3119 if (!is_server && socktype == SOCK_DGRAM)
3120 break;
3121 #endif /* DATAGRAM_SOCKETS */
3122
3123 #ifdef NON_BLOCKING_CONNECT
3124 if (is_non_blocking_client)
3125 {
3126 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3127 if (ret < 0)
3128 {
3129 xerrno = errno;
3130 emacs_close (s);
3131 s = -1;
3132 continue;
3133 }
3134 }
3135 #endif
3136
3137 /* Make us close S if quit. */
3138 record_unwind_protect (close_file_unwind, make_number (s));
3139
3140 /* Parse network options in the arg list.
3141 We simply ignore anything which isn't a known option (including other keywords).
3142 An error is signaled if setting a known option fails. */
3143 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3144 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3145
3146 if (is_server)
3147 {
3148 /* Configure as a server socket. */
3149
3150 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3151 explicit :reuseaddr key to override this. */
3152 #ifdef HAVE_LOCAL_SOCKETS
3153 if (family != AF_LOCAL)
3154 #endif
3155 if (!(optbits & (1 << OPIX_REUSEADDR)))
3156 {
3157 int optval = 1;
3158 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3159 report_file_error ("Cannot set reuse option on server socket", Qnil);
3160 }
3161
3162 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3163 report_file_error ("Cannot bind server socket", Qnil);
3164
3165 #ifdef HAVE_GETSOCKNAME
3166 if (EQ (service, Qt))
3167 {
3168 struct sockaddr_in sa1;
3169 socklen_t len1 = sizeof (sa1);
3170 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3171 {
3172 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3173 service = make_number (ntohs (sa1.sin_port));
3174 contact = Fplist_put (contact, QCservice, service);
3175 }
3176 }
3177 #endif
3178
3179 if (socktype != SOCK_DGRAM && listen (s, backlog))
3180 report_file_error ("Cannot listen on server socket", Qnil);
3181
3182 break;
3183 }
3184
3185 immediate_quit = 1;
3186 QUIT;
3187
3188 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3189 xerrno = errno;
3190
3191 if (ret == 0 || xerrno == EISCONN)
3192 {
3193 /* The unwind-protect will be discarded afterwards.
3194 Likewise for immediate_quit. */
3195 break;
3196 }
3197
3198 #ifdef NON_BLOCKING_CONNECT
3199 #ifdef EINPROGRESS
3200 if (is_non_blocking_client && xerrno == EINPROGRESS)
3201 break;
3202 #else
3203 #ifdef EWOULDBLOCK
3204 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3205 break;
3206 #endif
3207 #endif
3208 #endif
3209
3210 #ifndef WINDOWSNT
3211 if (xerrno == EINTR)
3212 {
3213 /* Unlike most other syscalls connect() cannot be called
3214 again. (That would return EALREADY.) The proper way to
3215 wait for completion is pselect(). */
3216 int sc;
3217 socklen_t len;
3218 SELECT_TYPE fdset;
3219 retry_select:
3220 FD_ZERO (&fdset);
3221 FD_SET (s, &fdset);
3222 QUIT;
3223 sc = pselect (s + 1, NULL, &fdset, NULL, NULL, NULL);
3224 if (sc == -1)
3225 {
3226 if (errno == EINTR)
3227 goto retry_select;
3228 else
3229 report_file_error ("select failed", Qnil);
3230 }
3231 eassert (sc > 0);
3232
3233 len = sizeof xerrno;
3234 eassert (FD_ISSET (s, &fdset));
3235 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3236 report_file_error ("getsockopt failed", Qnil);
3237 if (xerrno)
3238 errno = xerrno, report_file_error ("error during connect", Qnil);
3239 else
3240 break;
3241 }
3242 #endif /* !WINDOWSNT */
3243
3244 immediate_quit = 0;
3245
3246 /* Discard the unwind protect closing S. */
3247 specpdl_ptr = specpdl + count1;
3248 emacs_close (s);
3249 s = -1;
3250
3251 #ifdef WINDOWSNT
3252 if (xerrno == EINTR)
3253 goto retry_connect;
3254 #endif
3255 }
3256
3257 if (s >= 0)
3258 {
3259 #ifdef DATAGRAM_SOCKETS
3260 if (socktype == SOCK_DGRAM)
3261 {
3262 if (datagram_address[s].sa)
3263 emacs_abort ();
3264 datagram_address[s].sa = xmalloc (lres->ai_addrlen);
3265 datagram_address[s].len = lres->ai_addrlen;
3266 if (is_server)
3267 {
3268 Lisp_Object remote;
3269 memset (datagram_address[s].sa, 0, lres->ai_addrlen);
3270 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3271 {
3272 int rfamily, rlen;
3273 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3274 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3275 conv_lisp_to_sockaddr (rfamily, remote,
3276 datagram_address[s].sa, rlen);
3277 }
3278 }
3279 else
3280 memcpy (datagram_address[s].sa, lres->ai_addr, lres->ai_addrlen);
3281 }
3282 #endif
3283 contact = Fplist_put (contact, QCaddress,
3284 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3285 #ifdef HAVE_GETSOCKNAME
3286 if (!is_server)
3287 {
3288 struct sockaddr_in sa1;
3289 socklen_t len1 = sizeof (sa1);
3290 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3291 contact = Fplist_put (contact, QClocal,
3292 conv_sockaddr_to_lisp ((struct sockaddr *)&sa1, len1));
3293 }
3294 #endif
3295 }
3296
3297 immediate_quit = 0;
3298
3299 #ifdef HAVE_GETADDRINFO
3300 if (res != &ai)
3301 {
3302 block_input ();
3303 freeaddrinfo (res);
3304 unblock_input ();
3305 }
3306 #endif
3307
3308 /* Discard the unwind protect for closing S, if any. */
3309 specpdl_ptr = specpdl + count1;
3310
3311 /* Unwind bind_polling_period and request_sigio. */
3312 unbind_to (count, Qnil);
3313
3314 if (s < 0)
3315 {
3316 /* If non-blocking got this far - and failed - assume non-blocking is
3317 not supported after all. This is probably a wrong assumption, but
3318 the normal blocking calls to open-network-stream handles this error
3319 better. */
3320 if (is_non_blocking_client)
3321 return Qnil;
3322
3323 errno = xerrno;
3324 if (is_server)
3325 report_file_error ("make server process failed", contact);
3326 else
3327 report_file_error ("make client process failed", contact);
3328 }
3329
3330 inch = s;
3331 outch = s;
3332
3333 if (!NILP (buffer))
3334 buffer = Fget_buffer_create (buffer);
3335 proc = make_process (name);
3336
3337 chan_process[inch] = proc;
3338
3339 fcntl (inch, F_SETFL, O_NONBLOCK);
3340
3341 p = XPROCESS (proc);
3342
3343 pset_childp (p, contact);
3344 pset_plist (p, Fcopy_sequence (Fplist_get (contact, QCplist)));
3345 pset_type (p, Qnetwork);
3346
3347 pset_buffer (p, buffer);
3348 pset_sentinel (p, sentinel);
3349 pset_filter (p, filter);
3350 pset_log (p, Fplist_get (contact, QClog));
3351 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3352 p->kill_without_query = 1;
3353 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3354 pset_command (p, Qt);
3355 p->pid = 0;
3356 p->infd = inch;
3357 p->outfd = outch;
3358 if (is_server && socktype != SOCK_DGRAM)
3359 pset_status (p, Qlisten);
3360
3361 /* Make the process marker point into the process buffer (if any). */
3362 if (BUFFERP (buffer))
3363 set_marker_both (p->mark, buffer,
3364 BUF_ZV (XBUFFER (buffer)),
3365 BUF_ZV_BYTE (XBUFFER (buffer)));
3366
3367 #ifdef NON_BLOCKING_CONNECT
3368 if (is_non_blocking_client)
3369 {
3370 /* We may get here if connect did succeed immediately. However,
3371 in that case, we still need to signal this like a non-blocking
3372 connection. */
3373 pset_status (p, Qconnect);
3374 if (!FD_ISSET (inch, &connect_wait_mask))
3375 {
3376 FD_SET (inch, &connect_wait_mask);
3377 FD_SET (inch, &write_mask);
3378 num_pending_connects++;
3379 }
3380 }
3381 else
3382 #endif
3383 /* A server may have a client filter setting of Qt, but it must
3384 still listen for incoming connects unless it is stopped. */
3385 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3386 || (EQ (p->status, Qlisten) && NILP (p->command)))
3387 {
3388 FD_SET (inch, &input_wait_mask);
3389 FD_SET (inch, &non_keyboard_wait_mask);
3390 }
3391
3392 if (inch > max_process_desc)
3393 max_process_desc = inch;
3394
3395 tem = Fplist_member (contact, QCcoding);
3396 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3397 tem = Qnil; /* No error message (too late!). */
3398
3399 {
3400 /* Setup coding systems for communicating with the network stream. */
3401 struct gcpro gcpro1;
3402 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3403 Lisp_Object coding_systems = Qt;
3404 Lisp_Object fargs[5], val;
3405
3406 if (!NILP (tem))
3407 {
3408 val = XCAR (XCDR (tem));
3409 if (CONSP (val))
3410 val = XCAR (val);
3411 }
3412 else if (!NILP (Vcoding_system_for_read))
3413 val = Vcoding_system_for_read;
3414 else if ((!NILP (buffer) && NILP (BVAR (XBUFFER (buffer), enable_multibyte_characters)))
3415 || (NILP (buffer) && NILP (BVAR (&buffer_defaults, enable_multibyte_characters))))
3416 /* We dare not decode end-of-line format by setting VAL to
3417 Qraw_text, because the existing Emacs Lisp libraries
3418 assume that they receive bare code including a sequence of
3419 CR LF. */
3420 val = Qnil;
3421 else
3422 {
3423 if (NILP (host) || NILP (service))
3424 coding_systems = Qnil;
3425 else
3426 {
3427 fargs[0] = Qopen_network_stream, fargs[1] = name,
3428 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3429 GCPRO1 (proc);
3430 coding_systems = Ffind_operation_coding_system (5, fargs);
3431 UNGCPRO;
3432 }
3433 if (CONSP (coding_systems))
3434 val = XCAR (coding_systems);
3435 else if (CONSP (Vdefault_process_coding_system))
3436 val = XCAR (Vdefault_process_coding_system);
3437 else
3438 val = Qnil;
3439 }
3440 pset_decode_coding_system (p, val);
3441
3442 if (!NILP (tem))
3443 {
3444 val = XCAR (XCDR (tem));
3445 if (CONSP (val))
3446 val = XCDR (val);
3447 }
3448 else if (!NILP (Vcoding_system_for_write))
3449 val = Vcoding_system_for_write;
3450 else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
3451 val = Qnil;
3452 else
3453 {
3454 if (EQ (coding_systems, Qt))
3455 {
3456 if (NILP (host) || NILP (service))
3457 coding_systems = Qnil;
3458 else
3459 {
3460 fargs[0] = Qopen_network_stream, fargs[1] = name,
3461 fargs[2] = buffer, fargs[3] = host, fargs[4] = service;
3462 GCPRO1 (proc);
3463 coding_systems = Ffind_operation_coding_system (5, fargs);
3464 UNGCPRO;
3465 }
3466 }
3467 if (CONSP (coding_systems))
3468 val = XCDR (coding_systems);
3469 else if (CONSP (Vdefault_process_coding_system))
3470 val = XCDR (Vdefault_process_coding_system);
3471 else
3472 val = Qnil;
3473 }
3474 pset_encode_coding_system (p, val);
3475 }
3476 setup_process_coding_systems (proc);
3477
3478 pset_decoding_buf (p, empty_unibyte_string);
3479 p->decoding_carryover = 0;
3480 pset_encoding_buf (p, empty_unibyte_string);
3481
3482 p->inherit_coding_system_flag
3483 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3484
3485 UNGCPRO;
3486 return proc;
3487 }
3488
3489 \f
3490 #if defined (HAVE_NET_IF_H)
3491
3492 #ifdef SIOCGIFCONF
3493 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3494 doc: /* Return an alist of all network interfaces and their network address.
3495 Each element is a cons, the car of which is a string containing the
3496 interface name, and the cdr is the network address in internal
3497 format; see the description of ADDRESS in `make-network-process'. */)
3498 (void)
3499 {
3500 struct ifconf ifconf;
3501 struct ifreq *ifreq;
3502 void *buf = NULL;
3503 ptrdiff_t buf_size = 512;
3504 int s, i;
3505 Lisp_Object res;
3506
3507 s = socket (AF_INET, SOCK_STREAM, 0);
3508 if (s < 0)
3509 return Qnil;
3510
3511 do
3512 {
3513 buf = xpalloc (buf, &buf_size, 1, INT_MAX, 1);
3514 ifconf.ifc_buf = buf;
3515 ifconf.ifc_len = buf_size;
3516 if (ioctl (s, SIOCGIFCONF, &ifconf))
3517 {
3518 close (s);
3519 xfree (buf);
3520 return Qnil;
3521 }
3522 }
3523 while (ifconf.ifc_len == buf_size);
3524
3525 close (s);
3526
3527 res = Qnil;
3528 ifreq = ifconf.ifc_req;
3529 while ((char *) ifreq < (char *) ifconf.ifc_req + ifconf.ifc_len)
3530 {
3531 struct ifreq *ifq = ifreq;
3532 #ifdef HAVE_STRUCT_IFREQ_IFR_ADDR_SA_LEN
3533 #define SIZEOF_IFREQ(sif) \
3534 ((sif)->ifr_addr.sa_len < sizeof (struct sockaddr) \
3535 ? sizeof (*(sif)) : sizeof ((sif)->ifr_name) + (sif)->ifr_addr.sa_len)
3536
3537 int len = SIZEOF_IFREQ (ifq);
3538 #else
3539 int len = sizeof (*ifreq);
3540 #endif
3541 char namebuf[sizeof (ifq->ifr_name) + 1];
3542 i += len;
3543 ifreq = (struct ifreq *) ((char *) ifreq + len);
3544
3545 if (ifq->ifr_addr.sa_family != AF_INET)
3546 continue;
3547
3548 memcpy (namebuf, ifq->ifr_name, sizeof (ifq->ifr_name));
3549 namebuf[sizeof (ifq->ifr_name)] = 0;
3550 res = Fcons (Fcons (build_string (namebuf),
3551 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3552 sizeof (struct sockaddr))),
3553 res);
3554 }
3555
3556 xfree (buf);
3557 return res;
3558 }
3559 #endif /* SIOCGIFCONF */
3560
3561 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
3562
3563 struct ifflag_def {
3564 int flag_bit;
3565 const char *flag_sym;
3566 };
3567
3568 static const struct ifflag_def ifflag_table[] = {
3569 #ifdef IFF_UP
3570 { IFF_UP, "up" },
3571 #endif
3572 #ifdef IFF_BROADCAST
3573 { IFF_BROADCAST, "broadcast" },
3574 #endif
3575 #ifdef IFF_DEBUG
3576 { IFF_DEBUG, "debug" },
3577 #endif
3578 #ifdef IFF_LOOPBACK
3579 { IFF_LOOPBACK, "loopback" },
3580 #endif
3581 #ifdef IFF_POINTOPOINT
3582 { IFF_POINTOPOINT, "pointopoint" },
3583 #endif
3584 #ifdef IFF_RUNNING
3585 { IFF_RUNNING, "running" },
3586 #endif
3587 #ifdef IFF_NOARP
3588 { IFF_NOARP, "noarp" },
3589 #endif
3590 #ifdef IFF_PROMISC
3591 { IFF_PROMISC, "promisc" },
3592 #endif
3593 #ifdef IFF_NOTRAILERS
3594 #ifdef NS_IMPL_COCOA
3595 /* Really means smart, notrailers is obsolete */
3596 { IFF_NOTRAILERS, "smart" },
3597 #else
3598 { IFF_NOTRAILERS, "notrailers" },
3599 #endif
3600 #endif
3601 #ifdef IFF_ALLMULTI
3602 { IFF_ALLMULTI, "allmulti" },
3603 #endif
3604 #ifdef IFF_MASTER
3605 { IFF_MASTER, "master" },
3606 #endif
3607 #ifdef IFF_SLAVE
3608 { IFF_SLAVE, "slave" },
3609 #endif
3610 #ifdef IFF_MULTICAST
3611 { IFF_MULTICAST, "multicast" },
3612 #endif
3613 #ifdef IFF_PORTSEL
3614 { IFF_PORTSEL, "portsel" },
3615 #endif
3616 #ifdef IFF_AUTOMEDIA
3617 { IFF_AUTOMEDIA, "automedia" },
3618 #endif
3619 #ifdef IFF_DYNAMIC
3620 { IFF_DYNAMIC, "dynamic" },
3621 #endif
3622 #ifdef IFF_OACTIVE
3623 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3624 #endif
3625 #ifdef IFF_SIMPLEX
3626 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3627 #endif
3628 #ifdef IFF_LINK0
3629 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3630 #endif
3631 #ifdef IFF_LINK1
3632 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3633 #endif
3634 #ifdef IFF_LINK2
3635 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3636 #endif
3637 { 0, 0 }
3638 };
3639
3640 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3641 doc: /* Return information about network interface named IFNAME.
3642 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3643 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3644 NETMASK is the layer 3 network mask, HWADDR is the layer 2 address, and
3645 FLAGS is the current flags of the interface. */)
3646 (Lisp_Object ifname)
3647 {
3648 struct ifreq rq;
3649 Lisp_Object res = Qnil;
3650 Lisp_Object elt;
3651 int s;
3652 int any = 0;
3653 #if (! (defined SIOCGIFHWADDR && defined HAVE_STRUCT_IFREQ_IFR_HWADDR) \
3654 && defined HAVE_GETIFADDRS && defined LLADDR)
3655 struct ifaddrs *ifap;
3656 #endif
3657
3658 CHECK_STRING (ifname);
3659
3660 if (sizeof rq.ifr_name <= SBYTES (ifname))
3661 error ("interface name too long");
3662 strcpy (rq.ifr_name, SSDATA (ifname));
3663
3664 s = socket (AF_INET, SOCK_STREAM, 0);
3665 if (s < 0)
3666 return Qnil;
3667
3668 elt = Qnil;
3669 #if defined (SIOCGIFFLAGS) && defined (HAVE_STRUCT_IFREQ_IFR_FLAGS)
3670 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3671 {
3672 int flags = rq.ifr_flags;
3673 const struct ifflag_def *fp;
3674 int fnum;
3675
3676 /* If flags is smaller than int (i.e. short) it may have the high bit set
3677 due to IFF_MULTICAST. In that case, sign extending it into
3678 an int is wrong. */
3679 if (flags < 0 && sizeof (rq.ifr_flags) < sizeof (flags))
3680 flags = (unsigned short) rq.ifr_flags;
3681
3682 any = 1;
3683 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3684 {
3685 if (flags & fp->flag_bit)
3686 {
3687 elt = Fcons (intern (fp->flag_sym), elt);
3688 flags -= fp->flag_bit;
3689 }
3690 }
3691 for (fnum = 0; flags && fnum < 32; flags >>= 1, fnum++)
3692 {
3693 if (flags & 1)
3694 {
3695 elt = Fcons (make_number (fnum), elt);
3696 }
3697 }
3698 }
3699 #endif
3700 res = Fcons (elt, res);
3701
3702 elt = Qnil;
3703 #if defined (SIOCGIFHWADDR) && defined (HAVE_STRUCT_IFREQ_IFR_HWADDR)
3704 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
3705 {
3706 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3707 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3708 int n;
3709
3710 any = 1;
3711 for (n = 0; n < 6; n++)
3712 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
3713 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
3714 }
3715 #elif defined (HAVE_GETIFADDRS) && defined (LLADDR)
3716 if (getifaddrs (&ifap) != -1)
3717 {
3718 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
3719 register struct Lisp_Vector *p = XVECTOR (hwaddr);
3720 struct ifaddrs *it;
3721
3722 for (it = ifap; it != NULL; it = it->ifa_next)
3723 {
3724 struct sockaddr_dl *sdl = (struct sockaddr_dl*) it->ifa_addr;
3725 unsigned char linkaddr[6];
3726 int n;
3727
3728 if (it->ifa_addr->sa_family != AF_LINK
3729 || strcmp (it->ifa_name, SSDATA (ifname)) != 0
3730 || sdl->sdl_alen != 6)
3731 continue;
3732
3733 memcpy (linkaddr, LLADDR (sdl), sdl->sdl_alen);
3734 for (n = 0; n < 6; n++)
3735 p->contents[n] = make_number (linkaddr[n]);
3736
3737 elt = Fcons (make_number (it->ifa_addr->sa_family), hwaddr);
3738 break;
3739 }
3740 }
3741 #ifdef HAVE_FREEIFADDRS
3742 freeifaddrs (ifap);
3743 #endif
3744
3745 #endif /* HAVE_GETIFADDRS && LLADDR */
3746
3747 res = Fcons (elt, res);
3748
3749 elt = Qnil;
3750 #if defined (SIOCGIFNETMASK) && (defined (HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined (HAVE_STRUCT_IFREQ_IFR_ADDR))
3751 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
3752 {
3753 any = 1;
3754 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
3755 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
3756 #else
3757 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3758 #endif
3759 }
3760 #endif
3761 res = Fcons (elt, res);
3762
3763 elt = Qnil;
3764 #if defined (SIOCGIFBRDADDR) && defined (HAVE_STRUCT_IFREQ_IFR_BROADADDR)
3765 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
3766 {
3767 any = 1;
3768 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
3769 }
3770 #endif
3771 res = Fcons (elt, res);
3772
3773 elt = Qnil;
3774 #if defined (SIOCGIFADDR) && defined (HAVE_STRUCT_IFREQ_IFR_ADDR)
3775 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
3776 {
3777 any = 1;
3778 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
3779 }
3780 #endif
3781 res = Fcons (elt, res);
3782
3783 close (s);
3784
3785 return any ? res : Qnil;
3786 }
3787 #endif
3788 #endif /* defined (HAVE_NET_IF_H) */
3789
3790 /* Turn off input and output for process PROC. */
3791
3792 static void
3793 deactivate_process (Lisp_Object proc)
3794 {
3795 register int inchannel, outchannel;
3796 register struct Lisp_Process *p = XPROCESS (proc);
3797
3798 #ifdef HAVE_GNUTLS
3799 /* Delete GnuTLS structures in PROC, if any. */
3800 emacs_gnutls_deinit (proc);
3801 #endif /* HAVE_GNUTLS */
3802
3803 inchannel = p->infd;
3804 outchannel = p->outfd;
3805
3806 #ifdef ADAPTIVE_READ_BUFFERING
3807 if (p->read_output_delay > 0)
3808 {
3809 if (--process_output_delay_count < 0)
3810 process_output_delay_count = 0;
3811 p->read_output_delay = 0;
3812 p->read_output_skip = 0;
3813 }
3814 #endif
3815
3816 if (inchannel >= 0)
3817 {
3818 /* Beware SIGCHLD hereabouts. */
3819 flush_pending_output (inchannel);
3820 emacs_close (inchannel);
3821 if (outchannel >= 0 && outchannel != inchannel)
3822 emacs_close (outchannel);
3823
3824 p->infd = -1;
3825 p->outfd = -1;
3826 #ifdef DATAGRAM_SOCKETS
3827 if (DATAGRAM_CHAN_P (inchannel))
3828 {
3829 xfree (datagram_address[inchannel].sa);
3830 datagram_address[inchannel].sa = 0;
3831 datagram_address[inchannel].len = 0;
3832 }
3833 #endif
3834 chan_process[inchannel] = Qnil;
3835 FD_CLR (inchannel, &input_wait_mask);
3836 FD_CLR (inchannel, &non_keyboard_wait_mask);
3837 #ifdef NON_BLOCKING_CONNECT
3838 if (FD_ISSET (inchannel, &connect_wait_mask))
3839 {
3840 FD_CLR (inchannel, &connect_wait_mask);
3841 FD_CLR (inchannel, &write_mask);
3842 if (--num_pending_connects < 0)
3843 emacs_abort ();
3844 }
3845 #endif
3846 if (inchannel == max_process_desc)
3847 {
3848 int i;
3849 /* We just closed the highest-numbered process input descriptor,
3850 so recompute the highest-numbered one now. */
3851 max_process_desc = 0;
3852 for (i = 0; i < MAXDESC; i++)
3853 if (!NILP (chan_process[i]))
3854 max_process_desc = i;
3855 }
3856 }
3857 }
3858
3859 \f
3860 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3861 0, 4, 0,
3862 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3863 It is read into the process' buffers or given to their filter functions.
3864 Non-nil arg PROCESS means do not return until some output has been received
3865 from PROCESS.
3866
3867 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
3868 and milliseconds to wait; return after that much time whether or not
3869 there is any subprocess output. If SECONDS is a floating point number,
3870 it specifies a fractional number of seconds to wait.
3871 The MILLISEC argument is obsolete and should be avoided.
3872
3873 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
3874 from PROCESS, suspending reading output from other processes.
3875 If JUST-THIS-ONE is an integer, don't run any timers either.
3876 Return non-nil if we received any output before the timeout expired. */)
3877 (register Lisp_Object process, Lisp_Object seconds, Lisp_Object millisec, Lisp_Object just_this_one)
3878 {
3879 intmax_t secs;
3880 int nsecs;
3881
3882 if (! NILP (process))
3883 CHECK_PROCESS (process);
3884 else
3885 just_this_one = Qnil;
3886
3887 if (!NILP (millisec))
3888 { /* Obsolete calling convention using integers rather than floats. */
3889 CHECK_NUMBER (millisec);
3890 if (NILP (seconds))
3891 seconds = make_float (XINT (millisec) / 1000.0);
3892 else
3893 {
3894 CHECK_NUMBER (seconds);
3895 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
3896 }
3897 }
3898
3899 secs = 0;
3900 nsecs = -1;
3901
3902 if (!NILP (seconds))
3903 {
3904 if (INTEGERP (seconds))
3905 {
3906 if (0 < XINT (seconds))
3907 {
3908 secs = XINT (seconds);
3909 nsecs = 0;
3910 }
3911 }
3912 else if (FLOATP (seconds))
3913 {
3914 if (0 < XFLOAT_DATA (seconds))
3915 {
3916 EMACS_TIME t = EMACS_TIME_FROM_DOUBLE (XFLOAT_DATA (seconds));
3917 secs = min (EMACS_SECS (t), WAIT_READING_MAX);
3918 nsecs = EMACS_NSECS (t);
3919 }
3920 }
3921 else
3922 wrong_type_argument (Qnumberp, seconds);
3923 }
3924 else if (! NILP (process))
3925 nsecs = 0;
3926
3927 return
3928 (wait_reading_process_output (secs, nsecs, 0, 0,
3929 Qnil,
3930 !NILP (process) ? XPROCESS (process) : NULL,
3931 NILP (just_this_one) ? 0 :
3932 !INTEGERP (just_this_one) ? 1 : -1)
3933 ? Qt : Qnil);
3934 }
3935
3936 /* Accept a connection for server process SERVER on CHANNEL. */
3937
3938 static int connect_counter = 0;
3939
3940 static void
3941 server_accept_connection (Lisp_Object server, int channel)
3942 {
3943 Lisp_Object proc, caller, name, buffer;
3944 Lisp_Object contact, host, service;
3945 struct Lisp_Process *ps= XPROCESS (server);
3946 struct Lisp_Process *p;
3947 int s;
3948 union u_sockaddr {
3949 struct sockaddr sa;
3950 struct sockaddr_in in;
3951 #ifdef AF_INET6
3952 struct sockaddr_in6 in6;
3953 #endif
3954 #ifdef HAVE_LOCAL_SOCKETS
3955 struct sockaddr_un un;
3956 #endif
3957 } saddr;
3958 socklen_t len = sizeof saddr;
3959
3960 s = accept (channel, &saddr.sa, &len);
3961
3962 if (s < 0)
3963 {
3964 int code = errno;
3965
3966 if (code == EAGAIN)
3967 return;
3968 #ifdef EWOULDBLOCK
3969 if (code == EWOULDBLOCK)
3970 return;
3971 #endif
3972
3973 if (!NILP (ps->log))
3974 call3 (ps->log, server, Qnil,
3975 concat3 (build_string ("accept failed with code"),
3976 Fnumber_to_string (make_number (code)),
3977 build_string ("\n")));
3978 return;
3979 }
3980
3981 connect_counter++;
3982
3983 /* Setup a new process to handle the connection. */
3984
3985 /* Generate a unique identification of the caller, and build contact
3986 information for this process. */
3987 host = Qt;
3988 service = Qnil;
3989 switch (saddr.sa.sa_family)
3990 {
3991 case AF_INET:
3992 {
3993 Lisp_Object args[5];
3994 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
3995 args[0] = build_string ("%d.%d.%d.%d");
3996 args[1] = make_number (*ip++);
3997 args[2] = make_number (*ip++);
3998 args[3] = make_number (*ip++);
3999 args[4] = make_number (*ip++);
4000 host = Fformat (5, args);
4001 service = make_number (ntohs (saddr.in.sin_port));
4002
4003 args[0] = build_string (" <%s:%d>");
4004 args[1] = host;
4005 args[2] = service;
4006 caller = Fformat (3, args);
4007 }
4008 break;
4009
4010 #ifdef AF_INET6
4011 case AF_INET6:
4012 {
4013 Lisp_Object args[9];
4014 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4015 int i;
4016 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4017 for (i = 0; i < 8; i++)
4018 args[i+1] = make_number (ntohs (ip6[i]));
4019 host = Fformat (9, args);
4020 service = make_number (ntohs (saddr.in.sin_port));
4021
4022 args[0] = build_string (" <[%s]:%d>");
4023 args[1] = host;
4024 args[2] = service;
4025 caller = Fformat (3, args);
4026 }
4027 break;
4028 #endif
4029
4030 #ifdef HAVE_LOCAL_SOCKETS
4031 case AF_LOCAL:
4032 #endif
4033 default:
4034 caller = Fnumber_to_string (make_number (connect_counter));
4035 caller = concat3 (build_string (" <"), caller, build_string (">"));
4036 break;
4037 }
4038
4039 /* Create a new buffer name for this process if it doesn't have a
4040 filter. The new buffer name is based on the buffer name or
4041 process name of the server process concatenated with the caller
4042 identification. */
4043
4044 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4045 buffer = Qnil;
4046 else
4047 {
4048 buffer = ps->buffer;
4049 if (!NILP (buffer))
4050 buffer = Fbuffer_name (buffer);
4051 else
4052 buffer = ps->name;
4053 if (!NILP (buffer))
4054 {
4055 buffer = concat2 (buffer, caller);
4056 buffer = Fget_buffer_create (buffer);
4057 }
4058 }
4059
4060 /* Generate a unique name for the new server process. Combine the
4061 server process name with the caller identification. */
4062
4063 name = concat2 (ps->name, caller);
4064 proc = make_process (name);
4065
4066 chan_process[s] = proc;
4067
4068 fcntl (s, F_SETFL, O_NONBLOCK);
4069
4070 p = XPROCESS (proc);
4071
4072 /* Build new contact information for this setup. */
4073 contact = Fcopy_sequence (ps->childp);
4074 contact = Fplist_put (contact, QCserver, Qnil);
4075 contact = Fplist_put (contact, QChost, host);
4076 if (!NILP (service))
4077 contact = Fplist_put (contact, QCservice, service);
4078 contact = Fplist_put (contact, QCremote,
4079 conv_sockaddr_to_lisp (&saddr.sa, len));
4080 #ifdef HAVE_GETSOCKNAME
4081 len = sizeof saddr;
4082 if (getsockname (s, &saddr.sa, &len) == 0)
4083 contact = Fplist_put (contact, QClocal,
4084 conv_sockaddr_to_lisp (&saddr.sa, len));
4085 #endif
4086
4087 pset_childp (p, contact);
4088 pset_plist (p, Fcopy_sequence (ps->plist));
4089 pset_type (p, Qnetwork);
4090
4091 pset_buffer (p, buffer);
4092 pset_sentinel (p, ps->sentinel);
4093 pset_filter (p, ps->filter);
4094 pset_command (p, Qnil);
4095 p->pid = 0;
4096 p->infd = s;
4097 p->outfd = s;
4098 pset_status (p, Qrun);
4099
4100 /* Client processes for accepted connections are not stopped initially. */
4101 if (!EQ (p->filter, Qt))
4102 {
4103 FD_SET (s, &input_wait_mask);
4104 FD_SET (s, &non_keyboard_wait_mask);
4105 }
4106
4107 if (s > max_process_desc)
4108 max_process_desc = s;
4109
4110 /* Setup coding system for new process based on server process.
4111 This seems to be the proper thing to do, as the coding system
4112 of the new process should reflect the settings at the time the
4113 server socket was opened; not the current settings. */
4114
4115 pset_decode_coding_system (p, ps->decode_coding_system);
4116 pset_encode_coding_system (p, ps->encode_coding_system);
4117 setup_process_coding_systems (proc);
4118
4119 pset_decoding_buf (p, empty_unibyte_string);
4120 p->decoding_carryover = 0;
4121 pset_encoding_buf (p, empty_unibyte_string);
4122
4123 p->inherit_coding_system_flag
4124 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4125
4126 if (!NILP (ps->log))
4127 call3 (ps->log, server, proc,
4128 concat3 (build_string ("accept from "),
4129 (STRINGP (host) ? host : build_string ("-")),
4130 build_string ("\n")));
4131
4132 if (!NILP (p->sentinel))
4133 exec_sentinel (proc,
4134 concat3 (build_string ("open from "),
4135 (STRINGP (host) ? host : build_string ("-")),
4136 build_string ("\n")));
4137 }
4138
4139 /* This variable is different from waiting_for_input in keyboard.c.
4140 It is used to communicate to a lisp process-filter/sentinel (via the
4141 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4142 for user-input when that process-filter was called.
4143 waiting_for_input cannot be used as that is by definition 0 when
4144 lisp code is being evalled.
4145 This is also used in record_asynch_buffer_change.
4146 For that purpose, this must be 0
4147 when not inside wait_reading_process_output. */
4148 static int waiting_for_user_input_p;
4149
4150 static Lisp_Object
4151 wait_reading_process_output_unwind (Lisp_Object data)
4152 {
4153 waiting_for_user_input_p = XINT (data);
4154 return Qnil;
4155 }
4156
4157 /* This is here so breakpoints can be put on it. */
4158 static void
4159 wait_reading_process_output_1 (void)
4160 {
4161 }
4162
4163 /* Read and dispose of subprocess output while waiting for timeout to
4164 elapse and/or keyboard input to be available.
4165
4166 TIME_LIMIT is:
4167 timeout in seconds
4168 If negative, gobble data immediately available but don't wait for any.
4169
4170 NSECS is:
4171 an additional duration to wait, measured in nanoseconds
4172 If TIME_LIMIT is zero, then:
4173 If NSECS == 0, there is no limit.
4174 If NSECS > 0, the timeout consists of NSECS only.
4175 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
4176
4177 READ_KBD is:
4178 0 to ignore keyboard input, or
4179 1 to return when input is available, or
4180 -1 meaning caller will actually read the input, so don't throw to
4181 the quit handler, or
4182
4183 DO_DISPLAY means redisplay should be done to show subprocess
4184 output that arrives.
4185
4186 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4187 (and gobble terminal input into the buffer if any arrives).
4188
4189 If WAIT_PROC is specified, wait until something arrives from that
4190 process. The return value is true if we read some input from
4191 that process.
4192
4193 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4194 (suspending output from other processes). A negative value
4195 means don't run any timers either.
4196
4197 If WAIT_PROC is specified, then the function returns true if we
4198 received input from that process before the timeout elapsed.
4199 Otherwise, return true if we received input from any process. */
4200
4201 int
4202 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
4203 bool do_display,
4204 Lisp_Object wait_for_cell,
4205 struct Lisp_Process *wait_proc, int just_wait_proc)
4206 {
4207 register int channel, nfds;
4208 SELECT_TYPE Available;
4209 SELECT_TYPE Writeok;
4210 int check_write;
4211 int check_delay, no_avail;
4212 int xerrno;
4213 Lisp_Object proc;
4214 EMACS_TIME timeout, end_time;
4215 int wait_channel = -1;
4216 int got_some_input = 0;
4217 ptrdiff_t count = SPECPDL_INDEX ();
4218
4219 FD_ZERO (&Available);
4220 FD_ZERO (&Writeok);
4221
4222 if (time_limit == 0 && nsecs == 0 && wait_proc && !NILP (Vinhibit_quit)
4223 && !(CONSP (wait_proc->status)
4224 && EQ (XCAR (wait_proc->status), Qexit)))
4225 message ("Blocking call to accept-process-output with quit inhibited!!");
4226
4227 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4228 if (wait_proc != NULL)
4229 wait_channel = wait_proc->infd;
4230
4231 record_unwind_protect (wait_reading_process_output_unwind,
4232 make_number (waiting_for_user_input_p));
4233 waiting_for_user_input_p = read_kbd;
4234
4235 if (time_limit < 0)
4236 {
4237 time_limit = 0;
4238 nsecs = -1;
4239 }
4240 else if (TYPE_MAXIMUM (time_t) < time_limit)
4241 time_limit = TYPE_MAXIMUM (time_t);
4242
4243 /* Since we may need to wait several times,
4244 compute the absolute time to return at. */
4245 if (time_limit || 0 < nsecs)
4246 {
4247 timeout = make_emacs_time (time_limit, nsecs);
4248 end_time = add_emacs_time (current_emacs_time (), timeout);
4249 }
4250
4251 while (1)
4252 {
4253 int timeout_reduced_for_timers = 0;
4254
4255 /* If calling from keyboard input, do not quit
4256 since we want to return C-g as an input character.
4257 Otherwise, do pending quit if requested. */
4258 if (read_kbd >= 0)
4259 QUIT;
4260 else if (pending_signals)
4261 process_pending_signals ();
4262
4263 /* Exit now if the cell we're waiting for became non-nil. */
4264 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4265 break;
4266
4267 /* Compute time from now till when time limit is up */
4268 /* Exit if already run out */
4269 if (nsecs < 0)
4270 {
4271 /* A negative timeout means
4272 gobble output available now
4273 but don't wait at all. */
4274
4275 timeout = make_emacs_time (0, 0);
4276 }
4277 else if (time_limit || 0 < nsecs)
4278 {
4279 EMACS_TIME now = current_emacs_time ();
4280 if (EMACS_TIME_LE (end_time, now))
4281 break;
4282 timeout = sub_emacs_time (end_time, now);
4283 }
4284 else
4285 {
4286 timeout = make_emacs_time (100000, 0);
4287 }
4288
4289 /* Normally we run timers here.
4290 But not if wait_for_cell; in those cases,
4291 the wait is supposed to be short,
4292 and those callers cannot handle running arbitrary Lisp code here. */
4293 if (NILP (wait_for_cell)
4294 && just_wait_proc >= 0)
4295 {
4296 EMACS_TIME timer_delay;
4297
4298 do
4299 {
4300 unsigned old_timers_run = timers_run;
4301 struct buffer *old_buffer = current_buffer;
4302 Lisp_Object old_window = selected_window;
4303
4304 timer_delay = timer_check ();
4305
4306 /* If a timer has run, this might have changed buffers
4307 an alike. Make read_key_sequence aware of that. */
4308 if (timers_run != old_timers_run
4309 && (old_buffer != current_buffer
4310 || !EQ (old_window, selected_window))
4311 && waiting_for_user_input_p == -1)
4312 record_asynch_buffer_change ();
4313
4314 if (timers_run != old_timers_run && do_display)
4315 /* We must retry, since a timer may have requeued itself
4316 and that could alter the time_delay. */
4317 redisplay_preserve_echo_area (9);
4318 else
4319 break;
4320 }
4321 while (!detect_input_pending ());
4322
4323 /* If there is unread keyboard input, also return. */
4324 if (read_kbd != 0
4325 && requeued_events_pending_p ())
4326 break;
4327
4328 /* A negative timeout means do not wait at all. */
4329 if (0 <= nsecs)
4330 {
4331 if (EMACS_TIME_VALID_P (timer_delay))
4332 {
4333 if (EMACS_TIME_LT (timer_delay, timeout))
4334 {
4335 timeout = timer_delay;
4336 timeout_reduced_for_timers = 1;
4337 }
4338 }
4339 else
4340 {
4341 /* This is so a breakpoint can be put here. */
4342 wait_reading_process_output_1 ();
4343 }
4344 }
4345 }
4346
4347 /* Cause C-g and alarm signals to take immediate action,
4348 and cause input available signals to zero out timeout.
4349
4350 It is important that we do this before checking for process
4351 activity. If we get a SIGCHLD after the explicit checks for
4352 process activity, timeout is the only way we will know. */
4353 if (read_kbd < 0)
4354 set_waiting_for_input (&timeout);
4355
4356 /* If status of something has changed, and no input is
4357 available, notify the user of the change right away. After
4358 this explicit check, we'll let the SIGCHLD handler zap
4359 timeout to get our attention. */
4360 if (update_tick != process_tick)
4361 {
4362 SELECT_TYPE Atemp;
4363 SELECT_TYPE Ctemp;
4364
4365 if (kbd_on_hold_p ())
4366 FD_ZERO (&Atemp);
4367 else
4368 Atemp = input_wait_mask;
4369 Ctemp = write_mask;
4370
4371 timeout = make_emacs_time (0, 0);
4372 if ((pselect (max (max_process_desc, max_input_desc) + 1,
4373 &Atemp,
4374 #ifdef NON_BLOCKING_CONNECT
4375 (num_pending_connects > 0 ? &Ctemp : NULL),
4376 #else
4377 NULL,
4378 #endif
4379 NULL, &timeout, NULL)
4380 <= 0))
4381 {
4382 /* It's okay for us to do this and then continue with
4383 the loop, since timeout has already been zeroed out. */
4384 clear_waiting_for_input ();
4385 status_notify (NULL);
4386 if (do_display) redisplay_preserve_echo_area (13);
4387 }
4388 }
4389
4390 /* Don't wait for output from a non-running process. Just
4391 read whatever data has already been received. */
4392 if (wait_proc && wait_proc->raw_status_new)
4393 update_status (wait_proc);
4394 if (wait_proc
4395 && ! EQ (wait_proc->status, Qrun)
4396 && ! EQ (wait_proc->status, Qconnect))
4397 {
4398 int nread, total_nread = 0;
4399
4400 clear_waiting_for_input ();
4401 XSETPROCESS (proc, wait_proc);
4402
4403 /* Read data from the process, until we exhaust it. */
4404 while (wait_proc->infd >= 0)
4405 {
4406 nread = read_process_output (proc, wait_proc->infd);
4407
4408 if (nread == 0)
4409 break;
4410
4411 if (0 < nread)
4412 {
4413 total_nread += nread;
4414 got_some_input = 1;
4415 }
4416 else if (nread == -1 && (errno == EIO || errno == EAGAIN))
4417 break;
4418 #ifdef EWOULDBLOCK
4419 else if (nread == -1 && EWOULDBLOCK == errno)
4420 break;
4421 #endif
4422 }
4423 if (total_nread > 0 && do_display)
4424 redisplay_preserve_echo_area (10);
4425
4426 break;
4427 }
4428
4429 /* Wait till there is something to do */
4430
4431 if (wait_proc && just_wait_proc)
4432 {
4433 if (wait_proc->infd < 0) /* Terminated */
4434 break;
4435 FD_SET (wait_proc->infd, &Available);
4436 check_delay = 0;
4437 check_write = 0;
4438 }
4439 else if (!NILP (wait_for_cell))
4440 {
4441 Available = non_process_wait_mask;
4442 check_delay = 0;
4443 check_write = 0;
4444 }
4445 else
4446 {
4447 if (! read_kbd)
4448 Available = non_keyboard_wait_mask;
4449 else
4450 Available = input_wait_mask;
4451 Writeok = write_mask;
4452 #ifdef SELECT_CANT_DO_WRITE_MASK
4453 check_write = 0;
4454 #else
4455 check_write = 1;
4456 #endif
4457 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4458 }
4459
4460 /* If frame size has changed or the window is newly mapped,
4461 redisplay now, before we start to wait. There is a race
4462 condition here; if a SIGIO arrives between now and the select
4463 and indicates that a frame is trashed, the select may block
4464 displaying a trashed screen. */
4465 if (frame_garbaged && do_display)
4466 {
4467 clear_waiting_for_input ();
4468 redisplay_preserve_echo_area (11);
4469 if (read_kbd < 0)
4470 set_waiting_for_input (&timeout);
4471 }
4472
4473 /* Skip the `select' call if input is available and we're
4474 waiting for keyboard input or a cell change (which can be
4475 triggered by processing X events). In the latter case, set
4476 nfds to 1 to avoid breaking the loop. */
4477 no_avail = 0;
4478 if ((read_kbd || !NILP (wait_for_cell))
4479 && detect_input_pending ())
4480 {
4481 nfds = read_kbd ? 0 : 1;
4482 no_avail = 1;
4483 }
4484
4485 if (!no_avail)
4486 {
4487
4488 #ifdef ADAPTIVE_READ_BUFFERING
4489 /* Set the timeout for adaptive read buffering if any
4490 process has non-zero read_output_skip and non-zero
4491 read_output_delay, and we are not reading output for a
4492 specific wait_channel. It is not executed if
4493 Vprocess_adaptive_read_buffering is nil. */
4494 if (process_output_skip && check_delay > 0)
4495 {
4496 int nsecs = EMACS_NSECS (timeout);
4497 if (EMACS_SECS (timeout) > 0 || nsecs > READ_OUTPUT_DELAY_MAX)
4498 nsecs = READ_OUTPUT_DELAY_MAX;
4499 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4500 {
4501 proc = chan_process[channel];
4502 if (NILP (proc))
4503 continue;
4504 /* Find minimum non-zero read_output_delay among the
4505 processes with non-zero read_output_skip. */
4506 if (XPROCESS (proc)->read_output_delay > 0)
4507 {
4508 check_delay--;
4509 if (!XPROCESS (proc)->read_output_skip)
4510 continue;
4511 FD_CLR (channel, &Available);
4512 XPROCESS (proc)->read_output_skip = 0;
4513 if (XPROCESS (proc)->read_output_delay < nsecs)
4514 nsecs = XPROCESS (proc)->read_output_delay;
4515 }
4516 }
4517 timeout = make_emacs_time (0, nsecs);
4518 process_output_skip = 0;
4519 }
4520 #endif
4521
4522 #if defined (USE_GTK) || defined (HAVE_GCONF) || defined (HAVE_GSETTINGS)
4523 nfds = xg_select
4524 #elif defined (HAVE_NS)
4525 nfds = ns_select
4526 #else
4527 nfds = pselect
4528 #endif
4529 (max (max_process_desc, max_input_desc) + 1,
4530 &Available,
4531 (check_write ? &Writeok : (SELECT_TYPE *)0),
4532 NULL, &timeout, NULL);
4533
4534 #ifdef HAVE_GNUTLS
4535 /* GnuTLS buffers data internally. In lowat mode it leaves
4536 some data in the TCP buffers so that select works, but
4537 with custom pull/push functions we need to check if some
4538 data is available in the buffers manually. */
4539 if (nfds == 0)
4540 {
4541 if (! wait_proc)
4542 {
4543 /* We're not waiting on a specific process, so loop
4544 through all the channels and check for data.
4545 This is a workaround needed for some versions of
4546 the gnutls library -- 2.12.14 has been confirmed
4547 to need it. See
4548 http://comments.gmane.org/gmane.emacs.devel/145074 */
4549 for (channel = 0; channel < MAXDESC; ++channel)
4550 if (! NILP (chan_process[channel]))
4551 {
4552 struct Lisp_Process *p =
4553 XPROCESS (chan_process[channel]);
4554 if (p && p->gnutls_p && p->infd
4555 && ((emacs_gnutls_record_check_pending
4556 (p->gnutls_state))
4557 > 0))
4558 {
4559 nfds++;
4560 FD_SET (p->infd, &Available);
4561 }
4562 }
4563 }
4564 else
4565 {
4566 /* Check this specific channel. */
4567 if (wait_proc->gnutls_p /* Check for valid process. */
4568 /* Do we have pending data? */
4569 && ((emacs_gnutls_record_check_pending
4570 (wait_proc->gnutls_state))
4571 > 0))
4572 {
4573 nfds = 1;
4574 /* Set to Available. */
4575 FD_SET (wait_proc->infd, &Available);
4576 }
4577 }
4578 }
4579 #endif
4580 }
4581
4582 xerrno = errno;
4583
4584 /* Make C-g and alarm signals set flags again */
4585 clear_waiting_for_input ();
4586
4587 /* If we woke up due to SIGWINCH, actually change size now. */
4588 do_pending_window_change (0);
4589
4590 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
4591 /* We waited the full specified time, so return now. */
4592 break;
4593 if (nfds < 0)
4594 {
4595 if (xerrno == EINTR)
4596 no_avail = 1;
4597 else if (xerrno == EBADF)
4598 {
4599 #ifdef AIX
4600 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4601 the child's closure of the pts gives the parent a SIGHUP, and
4602 the ptc file descriptor is automatically closed,
4603 yielding EBADF here or at select() call above.
4604 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4605 in m/ibmrt-aix.h), and here we just ignore the select error.
4606 Cleanup occurs c/o status_notify after SIGCHLD. */
4607 no_avail = 1; /* Cannot depend on values returned */
4608 #else
4609 emacs_abort ();
4610 #endif
4611 }
4612 else
4613 error ("select error: %s", emacs_strerror (xerrno));
4614 }
4615
4616 if (no_avail)
4617 {
4618 FD_ZERO (&Available);
4619 check_write = 0;
4620 }
4621
4622 /* Check for keyboard input */
4623 /* If there is any, return immediately
4624 to give it higher priority than subprocesses */
4625
4626 if (read_kbd != 0)
4627 {
4628 unsigned old_timers_run = timers_run;
4629 struct buffer *old_buffer = current_buffer;
4630 Lisp_Object old_window = selected_window;
4631 int leave = 0;
4632
4633 if (detect_input_pending_run_timers (do_display))
4634 {
4635 swallow_events (do_display);
4636 if (detect_input_pending_run_timers (do_display))
4637 leave = 1;
4638 }
4639
4640 /* If a timer has run, this might have changed buffers
4641 an alike. Make read_key_sequence aware of that. */
4642 if (timers_run != old_timers_run
4643 && waiting_for_user_input_p == -1
4644 && (old_buffer != current_buffer
4645 || !EQ (old_window, selected_window)))
4646 record_asynch_buffer_change ();
4647
4648 if (leave)
4649 break;
4650 }
4651
4652 /* If there is unread keyboard input, also return. */
4653 if (read_kbd != 0
4654 && requeued_events_pending_p ())
4655 break;
4656
4657 /* If we are not checking for keyboard input now,
4658 do process events (but don't run any timers).
4659 This is so that X events will be processed.
4660 Otherwise they may have to wait until polling takes place.
4661 That would causes delays in pasting selections, for example.
4662
4663 (We used to do this only if wait_for_cell.) */
4664 if (read_kbd == 0 && detect_input_pending ())
4665 {
4666 swallow_events (do_display);
4667 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4668 if (detect_input_pending ())
4669 break;
4670 #endif
4671 }
4672
4673 /* Exit now if the cell we're waiting for became non-nil. */
4674 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4675 break;
4676
4677 #ifdef USABLE_SIGIO
4678 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4679 go read it. This can happen with X on BSD after logging out.
4680 In that case, there really is no input and no SIGIO,
4681 but select says there is input. */
4682
4683 if (read_kbd && interrupt_input
4684 && keyboard_bit_set (&Available) && ! noninteractive)
4685 handle_input_available_signal (SIGIO);
4686 #endif
4687
4688 if (! wait_proc)
4689 got_some_input |= nfds > 0;
4690
4691 /* If checking input just got us a size-change event from X,
4692 obey it now if we should. */
4693 if (read_kbd || ! NILP (wait_for_cell))
4694 do_pending_window_change (0);
4695
4696 /* Check for data from a process. */
4697 if (no_avail || nfds == 0)
4698 continue;
4699
4700 for (channel = 0; channel <= max_input_desc; ++channel)
4701 {
4702 struct fd_callback_data *d = &fd_callback_info[channel];
4703 if (d->func
4704 && ((d->condition & FOR_READ
4705 && FD_ISSET (channel, &Available))
4706 || (d->condition & FOR_WRITE
4707 && FD_ISSET (channel, &write_mask))))
4708 d->func (channel, d->data);
4709 }
4710
4711 for (channel = 0; channel <= max_process_desc; channel++)
4712 {
4713 if (FD_ISSET (channel, &Available)
4714 && FD_ISSET (channel, &non_keyboard_wait_mask)
4715 && !FD_ISSET (channel, &non_process_wait_mask))
4716 {
4717 int nread;
4718
4719 /* If waiting for this channel, arrange to return as
4720 soon as no more input to be processed. No more
4721 waiting. */
4722 if (wait_channel == channel)
4723 {
4724 wait_channel = -1;
4725 nsecs = -1;
4726 got_some_input = 1;
4727 }
4728 proc = chan_process[channel];
4729 if (NILP (proc))
4730 continue;
4731
4732 /* If this is a server stream socket, accept connection. */
4733 if (EQ (XPROCESS (proc)->status, Qlisten))
4734 {
4735 server_accept_connection (proc, channel);
4736 continue;
4737 }
4738
4739 /* Read data from the process, starting with our
4740 buffered-ahead character if we have one. */
4741
4742 nread = read_process_output (proc, channel);
4743 if (nread > 0)
4744 {
4745 /* Since read_process_output can run a filter,
4746 which can call accept-process-output,
4747 don't try to read from any other processes
4748 before doing the select again. */
4749 FD_ZERO (&Available);
4750
4751 if (do_display)
4752 redisplay_preserve_echo_area (12);
4753 }
4754 #ifdef EWOULDBLOCK
4755 else if (nread == -1 && errno == EWOULDBLOCK)
4756 ;
4757 #endif
4758 else if (nread == -1 && errno == EAGAIN)
4759 ;
4760 #ifdef WINDOWSNT
4761 /* FIXME: Is this special case still needed? */
4762 /* Note that we cannot distinguish between no input
4763 available now and a closed pipe.
4764 With luck, a closed pipe will be accompanied by
4765 subprocess termination and SIGCHLD. */
4766 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4767 ;
4768 #endif
4769 #ifdef HAVE_PTYS
4770 /* On some OSs with ptys, when the process on one end of
4771 a pty exits, the other end gets an error reading with
4772 errno = EIO instead of getting an EOF (0 bytes read).
4773 Therefore, if we get an error reading and errno =
4774 EIO, just continue, because the child process has
4775 exited and should clean itself up soon (e.g. when we
4776 get a SIGCHLD). */
4777 else if (nread == -1 && errno == EIO)
4778 {
4779 struct Lisp_Process *p = XPROCESS (proc);
4780
4781 /* Clear the descriptor now, so we only raise the
4782 signal once. */
4783 FD_CLR (channel, &input_wait_mask);
4784 FD_CLR (channel, &non_keyboard_wait_mask);
4785
4786 if (p->pid == -2)
4787 {
4788 /* If the EIO occurs on a pty, the SIGCHLD handler's
4789 waitpid call will not find the process object to
4790 delete. Do it here. */
4791 p->tick = ++process_tick;
4792 pset_status (p, Qfailed);
4793 }
4794 }
4795 #endif /* HAVE_PTYS */
4796 /* If we can detect process termination, don't consider the
4797 process gone just because its pipe is closed. */
4798 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
4799 ;
4800 else
4801 {
4802 /* Preserve status of processes already terminated. */
4803 XPROCESS (proc)->tick = ++process_tick;
4804 deactivate_process (proc);
4805 if (XPROCESS (proc)->raw_status_new)
4806 update_status (XPROCESS (proc));
4807 if (EQ (XPROCESS (proc)->status, Qrun))
4808 pset_status (XPROCESS (proc),
4809 list2 (Qexit, make_number (256)));
4810 }
4811 }
4812 #ifdef NON_BLOCKING_CONNECT
4813 if (FD_ISSET (channel, &Writeok)
4814 && FD_ISSET (channel, &connect_wait_mask))
4815 {
4816 struct Lisp_Process *p;
4817
4818 FD_CLR (channel, &connect_wait_mask);
4819 FD_CLR (channel, &write_mask);
4820 if (--num_pending_connects < 0)
4821 emacs_abort ();
4822
4823 proc = chan_process[channel];
4824 if (NILP (proc))
4825 continue;
4826
4827 p = XPROCESS (proc);
4828
4829 #ifdef GNU_LINUX
4830 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4831 So only use it on systems where it is known to work. */
4832 {
4833 socklen_t xlen = sizeof (xerrno);
4834 if (getsockopt (channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4835 xerrno = errno;
4836 }
4837 #else
4838 {
4839 struct sockaddr pname;
4840 int pnamelen = sizeof (pname);
4841
4842 /* If connection failed, getpeername will fail. */
4843 xerrno = 0;
4844 if (getpeername (channel, &pname, &pnamelen) < 0)
4845 {
4846 /* Obtain connect failure code through error slippage. */
4847 char dummy;
4848 xerrno = errno;
4849 if (errno == ENOTCONN && read (channel, &dummy, 1) < 0)
4850 xerrno = errno;
4851 }
4852 }
4853 #endif
4854 if (xerrno)
4855 {
4856 p->tick = ++process_tick;
4857 pset_status (p, list2 (Qfailed, make_number (xerrno)));
4858 deactivate_process (proc);
4859 }
4860 else
4861 {
4862 pset_status (p, Qrun);
4863 /* Execute the sentinel here. If we had relied on
4864 status_notify to do it later, it will read input
4865 from the process before calling the sentinel. */
4866 exec_sentinel (proc, build_string ("open\n"));
4867 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4868 {
4869 FD_SET (p->infd, &input_wait_mask);
4870 FD_SET (p->infd, &non_keyboard_wait_mask);
4871 }
4872 }
4873 }
4874 #endif /* NON_BLOCKING_CONNECT */
4875 } /* end for each file descriptor */
4876 } /* end while exit conditions not met */
4877
4878 unbind_to (count, Qnil);
4879
4880 /* If calling from keyboard input, do not quit
4881 since we want to return C-g as an input character.
4882 Otherwise, do pending quit if requested. */
4883 if (read_kbd >= 0)
4884 {
4885 /* Prevent input_pending from remaining set if we quit. */
4886 clear_input_pending ();
4887 QUIT;
4888 }
4889
4890 return got_some_input;
4891 }
4892 \f
4893 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4894
4895 static Lisp_Object
4896 read_process_output_call (Lisp_Object fun_and_args)
4897 {
4898 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4899 }
4900
4901 static Lisp_Object
4902 read_process_output_error_handler (Lisp_Object error_val)
4903 {
4904 cmd_error_internal (error_val, "error in process filter: ");
4905 Vinhibit_quit = Qt;
4906 update_echo_area ();
4907 Fsleep_for (make_number (2), Qnil);
4908 return Qt;
4909 }
4910
4911 /* Read pending output from the process channel,
4912 starting with our buffered-ahead character if we have one.
4913 Yield number of decoded characters read.
4914
4915 This function reads at most 4096 characters.
4916 If you want to read all available subprocess output,
4917 you must call it repeatedly until it returns zero.
4918
4919 The characters read are decoded according to PROC's coding-system
4920 for decoding. */
4921
4922 static int
4923 read_process_output (Lisp_Object proc, register int channel)
4924 {
4925 register ssize_t nbytes;
4926 char *chars;
4927 register Lisp_Object outstream;
4928 register struct Lisp_Process *p = XPROCESS (proc);
4929 register ptrdiff_t opoint;
4930 struct coding_system *coding = proc_decode_coding_system[channel];
4931 int carryover = p->decoding_carryover;
4932 int readmax = 4096;
4933 ptrdiff_t count = SPECPDL_INDEX ();
4934 Lisp_Object odeactivate;
4935
4936 chars = alloca (carryover + readmax);
4937 if (carryover)
4938 /* See the comment above. */
4939 memcpy (chars, SDATA (p->decoding_buf), carryover);
4940
4941 #ifdef DATAGRAM_SOCKETS
4942 /* We have a working select, so proc_buffered_char is always -1. */
4943 if (DATAGRAM_CHAN_P (channel))
4944 {
4945 socklen_t len = datagram_address[channel].len;
4946 nbytes = recvfrom (channel, chars + carryover, readmax,
4947 0, datagram_address[channel].sa, &len);
4948 }
4949 else
4950 #endif
4951 {
4952 int buffered = 0 <= proc_buffered_char[channel];
4953 if (buffered)
4954 {
4955 chars[carryover] = proc_buffered_char[channel];
4956 proc_buffered_char[channel] = -1;
4957 }
4958 #ifdef HAVE_GNUTLS
4959 if (p->gnutls_p)
4960 nbytes = emacs_gnutls_read (p, chars + carryover + buffered,
4961 readmax - buffered);
4962 else
4963 #endif
4964 nbytes = emacs_read (channel, chars + carryover + buffered,
4965 readmax - buffered);
4966 #ifdef ADAPTIVE_READ_BUFFERING
4967 if (nbytes > 0 && p->adaptive_read_buffering)
4968 {
4969 int delay = p->read_output_delay;
4970 if (nbytes < 256)
4971 {
4972 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
4973 {
4974 if (delay == 0)
4975 process_output_delay_count++;
4976 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
4977 }
4978 }
4979 else if (delay > 0 && nbytes == readmax - buffered)
4980 {
4981 delay -= READ_OUTPUT_DELAY_INCREMENT;
4982 if (delay == 0)
4983 process_output_delay_count--;
4984 }
4985 p->read_output_delay = delay;
4986 if (delay)
4987 {
4988 p->read_output_skip = 1;
4989 process_output_skip = 1;
4990 }
4991 }
4992 #endif
4993 nbytes += buffered;
4994 nbytes += buffered && nbytes <= 0;
4995 }
4996
4997 p->decoding_carryover = 0;
4998
4999 /* At this point, NBYTES holds number of bytes just received
5000 (including the one in proc_buffered_char[channel]). */
5001 if (nbytes <= 0)
5002 {
5003 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5004 return nbytes;
5005 coding->mode |= CODING_MODE_LAST_BLOCK;
5006 }
5007
5008 /* Now set NBYTES how many bytes we must decode. */
5009 nbytes += carryover;
5010
5011 odeactivate = Vdeactivate_mark;
5012 /* There's no good reason to let process filters change the current
5013 buffer, and many callers of accept-process-output, sit-for, and
5014 friends don't expect current-buffer to be changed from under them. */
5015 record_unwind_current_buffer ();
5016
5017 /* Read and dispose of the process output. */
5018 outstream = p->filter;
5019 if (!NILP (outstream))
5020 {
5021 Lisp_Object text;
5022 bool outer_running_asynch_code = running_asynch_code;
5023 int waiting = waiting_for_user_input_p;
5024
5025 /* No need to gcpro these, because all we do with them later
5026 is test them for EQness, and none of them should be a string. */
5027 #if 0
5028 Lisp_Object obuffer, okeymap;
5029 XSETBUFFER (obuffer, current_buffer);
5030 okeymap = BVAR (current_buffer, keymap);
5031 #endif
5032
5033 /* We inhibit quit here instead of just catching it so that
5034 hitting ^G when a filter happens to be running won't screw
5035 it up. */
5036 specbind (Qinhibit_quit, Qt);
5037 specbind (Qlast_nonmenu_event, Qt);
5038
5039 /* In case we get recursively called,
5040 and we already saved the match data nonrecursively,
5041 save the same match data in safely recursive fashion. */
5042 if (outer_running_asynch_code)
5043 {
5044 Lisp_Object tem;
5045 /* Don't clobber the CURRENT match data, either! */
5046 tem = Fmatch_data (Qnil, Qnil, Qnil);
5047 restore_search_regs ();
5048 record_unwind_save_match_data ();
5049 Fset_match_data (tem, Qt);
5050 }
5051
5052 /* For speed, if a search happens within this code,
5053 save the match data in a special nonrecursive fashion. */
5054 running_asynch_code = 1;
5055
5056 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5057 text = coding->dst_object;
5058 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5059 /* A new coding system might be found. */
5060 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5061 {
5062 pset_decode_coding_system (p, Vlast_coding_system_used);
5063
5064 /* Don't call setup_coding_system for
5065 proc_decode_coding_system[channel] here. It is done in
5066 detect_coding called via decode_coding above. */
5067
5068 /* If a coding system for encoding is not yet decided, we set
5069 it as the same as coding-system for decoding.
5070
5071 But, before doing that we must check if
5072 proc_encode_coding_system[p->outfd] surely points to a
5073 valid memory because p->outfd will be changed once EOF is
5074 sent to the process. */
5075 if (NILP (p->encode_coding_system)
5076 && proc_encode_coding_system[p->outfd])
5077 {
5078 pset_encode_coding_system
5079 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5080 setup_coding_system (p->encode_coding_system,
5081 proc_encode_coding_system[p->outfd]);
5082 }
5083 }
5084
5085 if (coding->carryover_bytes > 0)
5086 {
5087 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5088 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5089 memcpy (SDATA (p->decoding_buf), coding->carryover,
5090 coding->carryover_bytes);
5091 p->decoding_carryover = coding->carryover_bytes;
5092 }
5093 if (SBYTES (text) > 0)
5094 /* FIXME: It's wrong to wrap or not based on debug-on-error, and
5095 sometimes it's simply wrong to wrap (e.g. when called from
5096 accept-process-output). */
5097 internal_condition_case_1 (read_process_output_call,
5098 Fcons (outstream,
5099 Fcons (proc, Fcons (text, Qnil))),
5100 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5101 read_process_output_error_handler);
5102
5103 /* If we saved the match data nonrecursively, restore it now. */
5104 restore_search_regs ();
5105 running_asynch_code = outer_running_asynch_code;
5106
5107 /* Restore waiting_for_user_input_p as it was
5108 when we were called, in case the filter clobbered it. */
5109 waiting_for_user_input_p = waiting;
5110
5111 #if 0 /* Call record_asynch_buffer_change unconditionally,
5112 because we might have changed minor modes or other things
5113 that affect key bindings. */
5114 if (! EQ (Fcurrent_buffer (), obuffer)
5115 || ! EQ (current_buffer->keymap, okeymap))
5116 #endif
5117 /* But do it only if the caller is actually going to read events.
5118 Otherwise there's no need to make him wake up, and it could
5119 cause trouble (for example it would make sit_for return). */
5120 if (waiting_for_user_input_p == -1)
5121 record_asynch_buffer_change ();
5122 }
5123
5124 /* If no filter, write into buffer if it isn't dead. */
5125 else if (!NILP (p->buffer) && BUFFER_LIVE_P (XBUFFER (p->buffer)))
5126 {
5127 Lisp_Object old_read_only;
5128 ptrdiff_t old_begv, old_zv;
5129 ptrdiff_t old_begv_byte, old_zv_byte;
5130 ptrdiff_t before, before_byte;
5131 ptrdiff_t opoint_byte;
5132 Lisp_Object text;
5133 struct buffer *b;
5134
5135 Fset_buffer (p->buffer);
5136 opoint = PT;
5137 opoint_byte = PT_BYTE;
5138 old_read_only = BVAR (current_buffer, read_only);
5139 old_begv = BEGV;
5140 old_zv = ZV;
5141 old_begv_byte = BEGV_BYTE;
5142 old_zv_byte = ZV_BYTE;
5143
5144 bset_read_only (current_buffer, Qnil);
5145
5146 /* Insert new output into buffer
5147 at the current end-of-output marker,
5148 thus preserving logical ordering of input and output. */
5149 if (XMARKER (p->mark)->buffer)
5150 SET_PT_BOTH (clip_to_bounds (BEGV,
5151 marker_position (p->mark), ZV),
5152 clip_to_bounds (BEGV_BYTE,
5153 marker_byte_position (p->mark),
5154 ZV_BYTE));
5155 else
5156 SET_PT_BOTH (ZV, ZV_BYTE);
5157 before = PT;
5158 before_byte = PT_BYTE;
5159
5160 /* If the output marker is outside of the visible region, save
5161 the restriction and widen. */
5162 if (! (BEGV <= PT && PT <= ZV))
5163 Fwiden ();
5164
5165 decode_coding_c_string (coding, (unsigned char *) chars, nbytes, Qt);
5166 text = coding->dst_object;
5167 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5168 /* A new coding system might be found. See the comment in the
5169 similar code in the previous `if' block. */
5170 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5171 {
5172 pset_decode_coding_system (p, Vlast_coding_system_used);
5173 if (NILP (p->encode_coding_system)
5174 && proc_encode_coding_system[p->outfd])
5175 {
5176 pset_encode_coding_system
5177 (p, coding_inherit_eol_type (Vlast_coding_system_used, Qnil));
5178 setup_coding_system (p->encode_coding_system,
5179 proc_encode_coding_system[p->outfd]);
5180 }
5181 }
5182 if (coding->carryover_bytes > 0)
5183 {
5184 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5185 pset_decoding_buf (p, make_uninit_string (coding->carryover_bytes));
5186 memcpy (SDATA (p->decoding_buf), coding->carryover,
5187 coding->carryover_bytes);
5188 p->decoding_carryover = coding->carryover_bytes;
5189 }
5190 /* Adjust the multibyteness of TEXT to that of the buffer. */
5191 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
5192 != ! STRING_MULTIBYTE (text))
5193 text = (STRING_MULTIBYTE (text)
5194 ? Fstring_as_unibyte (text)
5195 : Fstring_to_multibyte (text));
5196 /* Insert before markers in case we are inserting where
5197 the buffer's mark is, and the user's next command is Meta-y. */
5198 insert_from_string_before_markers (text, 0, 0,
5199 SCHARS (text), SBYTES (text), 0);
5200
5201 /* Make sure the process marker's position is valid when the
5202 process buffer is changed in the signal_after_change above.
5203 W3 is known to do that. */
5204 if (BUFFERP (p->buffer)
5205 && (b = XBUFFER (p->buffer), b != current_buffer))
5206 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5207 else
5208 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5209
5210 update_mode_lines++;
5211
5212 /* Make sure opoint and the old restrictions
5213 float ahead of any new text just as point would. */
5214 if (opoint >= before)
5215 {
5216 opoint += PT - before;
5217 opoint_byte += PT_BYTE - before_byte;
5218 }
5219 if (old_begv > before)
5220 {
5221 old_begv += PT - before;
5222 old_begv_byte += PT_BYTE - before_byte;
5223 }
5224 if (old_zv >= before)
5225 {
5226 old_zv += PT - before;
5227 old_zv_byte += PT_BYTE - before_byte;
5228 }
5229
5230 /* If the restriction isn't what it should be, set it. */
5231 if (old_begv != BEGV || old_zv != ZV)
5232 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5233
5234
5235 bset_read_only (current_buffer, old_read_only);
5236 SET_PT_BOTH (opoint, opoint_byte);
5237 }
5238 /* Handling the process output should not deactivate the mark. */
5239 Vdeactivate_mark = odeactivate;
5240
5241 unbind_to (count, Qnil);
5242 return nbytes;
5243 }
5244 \f
5245 /* Sending data to subprocess */
5246
5247 /* In send_process, when a write fails temporarily,
5248 wait_reading_process_output is called. It may execute user code,
5249 e.g. timers, that attempts to write new data to the same process.
5250 We must ensure that data is sent in the right order, and not
5251 interspersed half-completed with other writes (Bug#10815). This is
5252 handled by the write_queue element of struct process. It is a list
5253 with each entry having the form
5254
5255 (string . (offset . length))
5256
5257 where STRING is a lisp string, OFFSET is the offset into the
5258 string's byte sequence from which we should begin to send, and
5259 LENGTH is the number of bytes left to send. */
5260
5261 /* Create a new entry in write_queue.
5262 INPUT_OBJ should be a buffer, string Qt, or Qnil.
5263 BUF is a pointer to the string sequence of the input_obj or a C
5264 string in case of Qt or Qnil. */
5265
5266 static void
5267 write_queue_push (struct Lisp_Process *p, Lisp_Object input_obj,
5268 const char *buf, ptrdiff_t len, int front)
5269 {
5270 ptrdiff_t offset;
5271 Lisp_Object entry, obj;
5272
5273 if (STRINGP (input_obj))
5274 {
5275 offset = buf - SSDATA (input_obj);
5276 obj = input_obj;
5277 }
5278 else
5279 {
5280 offset = 0;
5281 obj = make_unibyte_string (buf, len);
5282 }
5283
5284 entry = Fcons (obj, Fcons (make_number (offset), make_number (len)));
5285
5286 if (front)
5287 pset_write_queue (p, Fcons (entry, p->write_queue));
5288 else
5289 pset_write_queue (p, nconc2 (p->write_queue, Fcons (entry, Qnil)));
5290 }
5291
5292 /* Remove the first element in the write_queue of process P, put its
5293 contents in OBJ, BUF and LEN, and return non-zero. If the
5294 write_queue is empty, return zero. */
5295
5296 static int
5297 write_queue_pop (struct Lisp_Process *p, Lisp_Object *obj,
5298 const char **buf, ptrdiff_t *len)
5299 {
5300 Lisp_Object entry, offset_length;
5301 ptrdiff_t offset;
5302
5303 if (NILP (p->write_queue))
5304 return 0;
5305
5306 entry = XCAR (p->write_queue);
5307 pset_write_queue (p, XCDR (p->write_queue));
5308
5309 *obj = XCAR (entry);
5310 offset_length = XCDR (entry);
5311
5312 *len = XINT (XCDR (offset_length));
5313 offset = XINT (XCAR (offset_length));
5314 *buf = SSDATA (*obj) + offset;
5315
5316 return 1;
5317 }
5318
5319 /* Send some data to process PROC.
5320 BUF is the beginning of the data; LEN is the number of characters.
5321 OBJECT is the Lisp object that the data comes from. If OBJECT is
5322 nil or t, it means that the data comes from C string.
5323
5324 If OBJECT is not nil, the data is encoded by PROC's coding-system
5325 for encoding before it is sent.
5326
5327 This function can evaluate Lisp code and can garbage collect. */
5328
5329 static void
5330 send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
5331 Lisp_Object object)
5332 {
5333 struct Lisp_Process *p = XPROCESS (proc);
5334 ssize_t rv;
5335 struct coding_system *coding;
5336
5337 if (p->raw_status_new)
5338 update_status (p);
5339 if (! EQ (p->status, Qrun))
5340 error ("Process %s not running", SDATA (p->name));
5341 if (p->outfd < 0)
5342 error ("Output file descriptor of %s is closed", SDATA (p->name));
5343
5344 coding = proc_encode_coding_system[p->outfd];
5345 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5346
5347 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5348 || (BUFFERP (object)
5349 && !NILP (BVAR (XBUFFER (object), enable_multibyte_characters)))
5350 || EQ (object, Qt))
5351 {
5352 pset_encode_coding_system
5353 (p, complement_process_encoding_system (p->encode_coding_system));
5354 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5355 {
5356 /* The coding system for encoding was changed to raw-text
5357 because we sent a unibyte text previously. Now we are
5358 sending a multibyte text, thus we must encode it by the
5359 original coding system specified for the current process.
5360
5361 Another reason we come here is that the coding system
5362 was just complemented and a new one was returned by
5363 complement_process_encoding_system. */
5364 setup_coding_system (p->encode_coding_system, coding);
5365 Vlast_coding_system_used = p->encode_coding_system;
5366 }
5367 coding->src_multibyte = 1;
5368 }
5369 else
5370 {
5371 coding->src_multibyte = 0;
5372 /* For sending a unibyte text, character code conversion should
5373 not take place but EOL conversion should. So, setup raw-text
5374 or one of the subsidiary if we have not yet done it. */
5375 if (CODING_REQUIRE_ENCODING (coding))
5376 {
5377 if (CODING_REQUIRE_FLUSHING (coding))
5378 {
5379 /* But, before changing the coding, we must flush out data. */
5380 coding->mode |= CODING_MODE_LAST_BLOCK;
5381 send_process (proc, "", 0, Qt);
5382 coding->mode &= CODING_MODE_LAST_BLOCK;
5383 }
5384 setup_coding_system (raw_text_coding_system
5385 (Vlast_coding_system_used),
5386 coding);
5387 coding->src_multibyte = 0;
5388 }
5389 }
5390 coding->dst_multibyte = 0;
5391
5392 if (CODING_REQUIRE_ENCODING (coding))
5393 {
5394 coding->dst_object = Qt;
5395 if (BUFFERP (object))
5396 {
5397 ptrdiff_t from_byte, from, to;
5398 ptrdiff_t save_pt, save_pt_byte;
5399 struct buffer *cur = current_buffer;
5400
5401 set_buffer_internal (XBUFFER (object));
5402 save_pt = PT, save_pt_byte = PT_BYTE;
5403
5404 from_byte = PTR_BYTE_POS ((unsigned char *) buf);
5405 from = BYTE_TO_CHAR (from_byte);
5406 to = BYTE_TO_CHAR (from_byte + len);
5407 TEMP_SET_PT_BOTH (from, from_byte);
5408 encode_coding_object (coding, object, from, from_byte,
5409 to, from_byte + len, Qt);
5410 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5411 set_buffer_internal (cur);
5412 }
5413 else if (STRINGP (object))
5414 {
5415 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5416 SBYTES (object), Qt);
5417 }
5418 else
5419 {
5420 coding->dst_object = make_unibyte_string (buf, len);
5421 coding->produced = len;
5422 }
5423
5424 len = coding->produced;
5425 object = coding->dst_object;
5426 buf = SSDATA (object);
5427 }
5428
5429 /* If there is already data in the write_queue, put the new data
5430 in the back of queue. Otherwise, ignore it. */
5431 if (!NILP (p->write_queue))
5432 write_queue_push (p, object, buf, len, 0);
5433
5434 do /* while !NILP (p->write_queue) */
5435 {
5436 ptrdiff_t cur_len = -1;
5437 const char *cur_buf;
5438 Lisp_Object cur_object;
5439
5440 /* If write_queue is empty, ignore it. */
5441 if (!write_queue_pop (p, &cur_object, &cur_buf, &cur_len))
5442 {
5443 cur_len = len;
5444 cur_buf = buf;
5445 cur_object = object;
5446 }
5447
5448 while (cur_len > 0)
5449 {
5450 /* Send this batch, using one or more write calls. */
5451 ptrdiff_t written = 0;
5452 int outfd = p->outfd;
5453 #ifdef DATAGRAM_SOCKETS
5454 if (DATAGRAM_CHAN_P (outfd))
5455 {
5456 rv = sendto (outfd, cur_buf, cur_len,
5457 0, datagram_address[outfd].sa,
5458 datagram_address[outfd].len);
5459 if (0 <= rv)
5460 written = rv;
5461 else if (errno == EMSGSIZE)
5462 report_file_error ("sending datagram", Fcons (proc, Qnil));
5463 }
5464 else
5465 #endif
5466 {
5467 #ifdef HAVE_GNUTLS
5468 if (p->gnutls_p)
5469 written = emacs_gnutls_write (p, cur_buf, cur_len);
5470 else
5471 #endif
5472 written = emacs_write (outfd, cur_buf, cur_len);
5473 rv = (written ? 0 : -1);
5474 #ifdef ADAPTIVE_READ_BUFFERING
5475 if (p->read_output_delay > 0
5476 && p->adaptive_read_buffering == 1)
5477 {
5478 p->read_output_delay = 0;
5479 process_output_delay_count--;
5480 p->read_output_skip = 0;
5481 }
5482 #endif
5483 }
5484
5485 if (rv < 0)
5486 {
5487 if (errno == EAGAIN
5488 #ifdef EWOULDBLOCK
5489 || errno == EWOULDBLOCK
5490 #endif
5491 )
5492 /* Buffer is full. Wait, accepting input;
5493 that may allow the program
5494 to finish doing output and read more. */
5495 {
5496 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5497 /* A gross hack to work around a bug in FreeBSD.
5498 In the following sequence, read(2) returns
5499 bogus data:
5500
5501 write(2) 1022 bytes
5502 write(2) 954 bytes, get EAGAIN
5503 read(2) 1024 bytes in process_read_output
5504 read(2) 11 bytes in process_read_output
5505
5506 That is, read(2) returns more bytes than have
5507 ever been written successfully. The 1033 bytes
5508 read are the 1022 bytes written successfully
5509 after processing (for example with CRs added if
5510 the terminal is set up that way which it is
5511 here). The same bytes will be seen again in a
5512 later read(2), without the CRs. */
5513
5514 if (errno == EAGAIN)
5515 {
5516 int flags = FWRITE;
5517 ioctl (p->outfd, TIOCFLUSH, &flags);
5518 }
5519 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5520
5521 /* Put what we should have written in wait_queue. */
5522 write_queue_push (p, cur_object, cur_buf, cur_len, 1);
5523 wait_reading_process_output (0, 20 * 1000 * 1000,
5524 0, 0, Qnil, NULL, 0);
5525 /* Reread queue, to see what is left. */
5526 break;
5527 }
5528 else if (errno == EPIPE)
5529 {
5530 p->raw_status_new = 0;
5531 pset_status (p, list2 (Qexit, make_number (256)));
5532 p->tick = ++process_tick;
5533 deactivate_process (proc);
5534 error ("process %s no longer connected to pipe; closed it",
5535 SDATA (p->name));
5536 }
5537 else
5538 /* This is a real error. */
5539 report_file_error ("writing to process", Fcons (proc, Qnil));
5540 }
5541 cur_buf += written;
5542 cur_len -= written;
5543 }
5544 }
5545 while (!NILP (p->write_queue));
5546 }
5547
5548 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5549 3, 3, 0,
5550 doc: /* Send current contents of region as input to PROCESS.
5551 PROCESS may be a process, a buffer, the name of a process or buffer, or
5552 nil, indicating the current buffer's process.
5553 Called from program, takes three arguments, PROCESS, START and END.
5554 If the region is more than 500 characters long,
5555 it is sent in several bunches. This may happen even for shorter regions.
5556 Output from processes can arrive in between bunches. */)
5557 (Lisp_Object process, Lisp_Object start, Lisp_Object end)
5558 {
5559 Lisp_Object proc = get_process (process);
5560 ptrdiff_t start_byte, end_byte;
5561
5562 validate_region (&start, &end);
5563
5564 start_byte = CHAR_TO_BYTE (XINT (start));
5565 end_byte = CHAR_TO_BYTE (XINT (end));
5566
5567 if (XINT (start) < GPT && XINT (end) > GPT)
5568 move_gap_both (XINT (start), start_byte);
5569
5570 send_process (proc, (char *) BYTE_POS_ADDR (start_byte),
5571 end_byte - start_byte, Fcurrent_buffer ());
5572
5573 return Qnil;
5574 }
5575
5576 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5577 2, 2, 0,
5578 doc: /* Send PROCESS the contents of STRING as input.
5579 PROCESS may be a process, a buffer, the name of a process or buffer, or
5580 nil, indicating the current buffer's process.
5581 If STRING is more than 500 characters long,
5582 it is sent in several bunches. This may happen even for shorter strings.
5583 Output from processes can arrive in between bunches. */)
5584 (Lisp_Object process, Lisp_Object string)
5585 {
5586 Lisp_Object proc;
5587 CHECK_STRING (string);
5588 proc = get_process (process);
5589 send_process (proc, SSDATA (string),
5590 SBYTES (string), string);
5591 return Qnil;
5592 }
5593 \f
5594 /* Return the foreground process group for the tty/pty that
5595 the process P uses. */
5596 static pid_t
5597 emacs_get_tty_pgrp (struct Lisp_Process *p)
5598 {
5599 pid_t gid = -1;
5600
5601 #ifdef TIOCGPGRP
5602 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5603 {
5604 int fd;
5605 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5606 master side. Try the slave side. */
5607 fd = emacs_open (SSDATA (p->tty_name), O_RDONLY, 0);
5608
5609 if (fd != -1)
5610 {
5611 ioctl (fd, TIOCGPGRP, &gid);
5612 emacs_close (fd);
5613 }
5614 }
5615 #endif /* defined (TIOCGPGRP ) */
5616
5617 return gid;
5618 }
5619
5620 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5621 Sprocess_running_child_p, 0, 1, 0,
5622 doc: /* Return t if PROCESS has given the terminal to a child.
5623 If the operating system does not make it possible to find out,
5624 return t unconditionally. */)
5625 (Lisp_Object process)
5626 {
5627 /* Initialize in case ioctl doesn't exist or gives an error,
5628 in a way that will cause returning t. */
5629 pid_t gid;
5630 Lisp_Object proc;
5631 struct Lisp_Process *p;
5632
5633 proc = get_process (process);
5634 p = XPROCESS (proc);
5635
5636 if (!EQ (p->type, Qreal))
5637 error ("Process %s is not a subprocess",
5638 SDATA (p->name));
5639 if (p->infd < 0)
5640 error ("Process %s is not active",
5641 SDATA (p->name));
5642
5643 gid = emacs_get_tty_pgrp (p);
5644
5645 if (gid == p->pid)
5646 return Qnil;
5647 return Qt;
5648 }
5649 \f
5650 /* send a signal number SIGNO to PROCESS.
5651 If CURRENT_GROUP is t, that means send to the process group
5652 that currently owns the terminal being used to communicate with PROCESS.
5653 This is used for various commands in shell mode.
5654 If CURRENT_GROUP is lambda, that means send to the process group
5655 that currently owns the terminal, but only if it is NOT the shell itself.
5656
5657 If NOMSG is zero, insert signal-announcements into process's buffers
5658 right away.
5659
5660 If we can, we try to signal PROCESS by sending control characters
5661 down the pty. This allows us to signal inferiors who have changed
5662 their uid, for which kill would return an EPERM error. */
5663
5664 static void
5665 process_send_signal (Lisp_Object process, int signo, Lisp_Object current_group,
5666 int nomsg)
5667 {
5668 Lisp_Object proc;
5669 register struct Lisp_Process *p;
5670 pid_t gid;
5671 int no_pgrp = 0;
5672
5673 proc = get_process (process);
5674 p = XPROCESS (proc);
5675
5676 if (!EQ (p->type, Qreal))
5677 error ("Process %s is not a subprocess",
5678 SDATA (p->name));
5679 if (p->infd < 0)
5680 error ("Process %s is not active",
5681 SDATA (p->name));
5682
5683 if (!p->pty_flag)
5684 current_group = Qnil;
5685
5686 /* If we are using pgrps, get a pgrp number and make it negative. */
5687 if (NILP (current_group))
5688 /* Send the signal to the shell's process group. */
5689 gid = p->pid;
5690 else
5691 {
5692 #ifdef SIGNALS_VIA_CHARACTERS
5693 /* If possible, send signals to the entire pgrp
5694 by sending an input character to it. */
5695
5696 struct termios t;
5697 cc_t *sig_char = NULL;
5698
5699 tcgetattr (p->infd, &t);
5700
5701 switch (signo)
5702 {
5703 case SIGINT:
5704 sig_char = &t.c_cc[VINTR];
5705 break;
5706
5707 case SIGQUIT:
5708 sig_char = &t.c_cc[VQUIT];
5709 break;
5710
5711 case SIGTSTP:
5712 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5713 sig_char = &t.c_cc[VSWTCH];
5714 #else
5715 sig_char = &t.c_cc[VSUSP];
5716 #endif
5717 break;
5718 }
5719
5720 if (sig_char && *sig_char != CDISABLE)
5721 {
5722 send_process (proc, (char *) sig_char, 1, Qnil);
5723 return;
5724 }
5725 /* If we can't send the signal with a character,
5726 fall through and send it another way. */
5727
5728 /* The code above may fall through if it can't
5729 handle the signal. */
5730 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5731
5732 #ifdef TIOCGPGRP
5733 /* Get the current pgrp using the tty itself, if we have that.
5734 Otherwise, use the pty to get the pgrp.
5735 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5736 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5737 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5738 His patch indicates that if TIOCGPGRP returns an error, then
5739 we should just assume that p->pid is also the process group id. */
5740
5741 gid = emacs_get_tty_pgrp (p);
5742
5743 if (gid == -1)
5744 /* If we can't get the information, assume
5745 the shell owns the tty. */
5746 gid = p->pid;
5747
5748 /* It is not clear whether anything really can set GID to -1.
5749 Perhaps on some system one of those ioctls can or could do so.
5750 Or perhaps this is vestigial. */
5751 if (gid == -1)
5752 no_pgrp = 1;
5753 #else /* ! defined (TIOCGPGRP ) */
5754 /* Can't select pgrps on this system, so we know that
5755 the child itself heads the pgrp. */
5756 gid = p->pid;
5757 #endif /* ! defined (TIOCGPGRP ) */
5758
5759 /* If current_group is lambda, and the shell owns the terminal,
5760 don't send any signal. */
5761 if (EQ (current_group, Qlambda) && gid == p->pid)
5762 return;
5763 }
5764
5765 switch (signo)
5766 {
5767 #ifdef SIGCONT
5768 case SIGCONT:
5769 p->raw_status_new = 0;
5770 pset_status (p, Qrun);
5771 p->tick = ++process_tick;
5772 if (!nomsg)
5773 {
5774 status_notify (NULL);
5775 redisplay_preserve_echo_area (13);
5776 }
5777 break;
5778 #endif /* ! defined (SIGCONT) */
5779 case SIGINT:
5780 case SIGQUIT:
5781 case SIGKILL:
5782 flush_pending_output (p->infd);
5783 break;
5784 }
5785
5786 /* If we don't have process groups, send the signal to the immediate
5787 subprocess. That isn't really right, but it's better than any
5788 obvious alternative. */
5789 if (no_pgrp)
5790 {
5791 kill (p->pid, signo);
5792 return;
5793 }
5794
5795 /* gid may be a pid, or minus a pgrp's number */
5796 #ifdef TIOCSIGSEND
5797 if (!NILP (current_group))
5798 {
5799 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5800 kill (-gid, signo);
5801 }
5802 else
5803 {
5804 gid = - p->pid;
5805 kill (gid, signo);
5806 }
5807 #else /* ! defined (TIOCSIGSEND) */
5808 kill (-gid, signo);
5809 #endif /* ! defined (TIOCSIGSEND) */
5810 }
5811
5812 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5813 doc: /* Interrupt process PROCESS.
5814 PROCESS may be a process, a buffer, or the name of a process or buffer.
5815 No arg or nil means current buffer's process.
5816 Second arg CURRENT-GROUP non-nil means send signal to
5817 the current process-group of the process's controlling terminal
5818 rather than to the process's own process group.
5819 If the process is a shell, this means interrupt current subjob
5820 rather than the shell.
5821
5822 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5823 don't send the signal. */)
5824 (Lisp_Object process, Lisp_Object current_group)
5825 {
5826 process_send_signal (process, SIGINT, current_group, 0);
5827 return process;
5828 }
5829
5830 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5831 doc: /* Kill process PROCESS. May be process or name of one.
5832 See function `interrupt-process' for more details on usage. */)
5833 (Lisp_Object process, Lisp_Object current_group)
5834 {
5835 process_send_signal (process, SIGKILL, current_group, 0);
5836 return process;
5837 }
5838
5839 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5840 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5841 See function `interrupt-process' for more details on usage. */)
5842 (Lisp_Object process, Lisp_Object current_group)
5843 {
5844 process_send_signal (process, SIGQUIT, current_group, 0);
5845 return process;
5846 }
5847
5848 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5849 doc: /* Stop process PROCESS. May be process or name of one.
5850 See function `interrupt-process' for more details on usage.
5851 If PROCESS is a network or serial process, inhibit handling of incoming
5852 traffic. */)
5853 (Lisp_Object process, Lisp_Object current_group)
5854 {
5855 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5856 {
5857 struct Lisp_Process *p;
5858
5859 p = XPROCESS (process);
5860 if (NILP (p->command)
5861 && p->infd >= 0)
5862 {
5863 FD_CLR (p->infd, &input_wait_mask);
5864 FD_CLR (p->infd, &non_keyboard_wait_mask);
5865 }
5866 pset_command (p, Qt);
5867 return process;
5868 }
5869 #ifndef SIGTSTP
5870 error ("No SIGTSTP support");
5871 #else
5872 process_send_signal (process, SIGTSTP, current_group, 0);
5873 #endif
5874 return process;
5875 }
5876
5877 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5878 doc: /* Continue process PROCESS. May be process or name of one.
5879 See function `interrupt-process' for more details on usage.
5880 If PROCESS is a network or serial process, resume handling of incoming
5881 traffic. */)
5882 (Lisp_Object process, Lisp_Object current_group)
5883 {
5884 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
5885 {
5886 struct Lisp_Process *p;
5887
5888 p = XPROCESS (process);
5889 if (EQ (p->command, Qt)
5890 && p->infd >= 0
5891 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5892 {
5893 FD_SET (p->infd, &input_wait_mask);
5894 FD_SET (p->infd, &non_keyboard_wait_mask);
5895 #ifdef WINDOWSNT
5896 if (fd_info[ p->infd ].flags & FILE_SERIAL)
5897 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
5898 #else /* not WINDOWSNT */
5899 tcflush (p->infd, TCIFLUSH);
5900 #endif /* not WINDOWSNT */
5901 }
5902 pset_command (p, Qnil);
5903 return process;
5904 }
5905 #ifdef SIGCONT
5906 process_send_signal (process, SIGCONT, current_group, 0);
5907 #else
5908 error ("No SIGCONT support");
5909 #endif
5910 return process;
5911 }
5912
5913 /* Return the integer value of the signal whose abbreviation is ABBR,
5914 or a negative number if there is no such signal. */
5915 static int
5916 abbr_to_signal (char const *name)
5917 {
5918 int i, signo;
5919 char sigbuf[20]; /* Large enough for all valid signal abbreviations. */
5920
5921 if (!strncmp (name, "SIG", 3) || !strncmp (name, "sig", 3))
5922 name += 3;
5923
5924 for (i = 0; i < sizeof sigbuf; i++)
5925 {
5926 sigbuf[i] = c_toupper (name[i]);
5927 if (! sigbuf[i])
5928 return str2sig (sigbuf, &signo) == 0 ? signo : -1;
5929 }
5930
5931 return -1;
5932 }
5933
5934 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5935 2, 2, "sProcess (name or number): \nnSignal code: ",
5936 doc: /* Send PROCESS the signal with code SIGCODE.
5937 PROCESS may also be a number specifying the process id of the
5938 process to signal; in this case, the process need not be a child of
5939 this Emacs.
5940 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5941 (Lisp_Object process, Lisp_Object sigcode)
5942 {
5943 pid_t pid;
5944 int signo;
5945
5946 if (STRINGP (process))
5947 {
5948 Lisp_Object tem = Fget_process (process);
5949 if (NILP (tem))
5950 {
5951 Lisp_Object process_number =
5952 string_to_number (SSDATA (process), 10, 1);
5953 if (INTEGERP (process_number) || FLOATP (process_number))
5954 tem = process_number;
5955 }
5956 process = tem;
5957 }
5958 else if (!NUMBERP (process))
5959 process = get_process (process);
5960
5961 if (NILP (process))
5962 return process;
5963
5964 if (NUMBERP (process))
5965 CONS_TO_INTEGER (process, pid_t, pid);
5966 else
5967 {
5968 CHECK_PROCESS (process);
5969 pid = XPROCESS (process)->pid;
5970 if (pid <= 0)
5971 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5972 }
5973
5974 if (INTEGERP (sigcode))
5975 {
5976 CHECK_TYPE_RANGED_INTEGER (int, sigcode);
5977 signo = XINT (sigcode);
5978 }
5979 else
5980 {
5981 char *name;
5982
5983 CHECK_SYMBOL (sigcode);
5984 name = SSDATA (SYMBOL_NAME (sigcode));
5985
5986 signo = abbr_to_signal (name);
5987 if (signo < 0)
5988 error ("Undefined signal name %s", name);
5989 }
5990
5991 return make_number (kill (pid, signo));
5992 }
5993
5994 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
5995 doc: /* Make PROCESS see end-of-file in its input.
5996 EOF comes after any text already sent to it.
5997 PROCESS may be a process, a buffer, the name of a process or buffer, or
5998 nil, indicating the current buffer's process.
5999 If PROCESS is a network connection, or is a process communicating
6000 through a pipe (as opposed to a pty), then you cannot send any more
6001 text to PROCESS after you call this function.
6002 If PROCESS is a serial process, wait until all output written to the
6003 process has been transmitted to the serial port. */)
6004 (Lisp_Object process)
6005 {
6006 Lisp_Object proc;
6007 struct coding_system *coding;
6008
6009 if (DATAGRAM_CONN_P (process))
6010 return process;
6011
6012 proc = get_process (process);
6013 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6014
6015 /* Make sure the process is really alive. */
6016 if (XPROCESS (proc)->raw_status_new)
6017 update_status (XPROCESS (proc));
6018 if (! EQ (XPROCESS (proc)->status, Qrun))
6019 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6020
6021 if (CODING_REQUIRE_FLUSHING (coding))
6022 {
6023 coding->mode |= CODING_MODE_LAST_BLOCK;
6024 send_process (proc, "", 0, Qnil);
6025 }
6026
6027 if (XPROCESS (proc)->pty_flag)
6028 send_process (proc, "\004", 1, Qnil);
6029 else if (EQ (XPROCESS (proc)->type, Qserial))
6030 {
6031 #ifndef WINDOWSNT
6032 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6033 error ("tcdrain() failed: %s", emacs_strerror (errno));
6034 #endif /* not WINDOWSNT */
6035 /* Do nothing on Windows because writes are blocking. */
6036 }
6037 else
6038 {
6039 int old_outfd, new_outfd;
6040
6041 #ifdef HAVE_SHUTDOWN
6042 /* If this is a network connection, or socketpair is used
6043 for communication with the subprocess, call shutdown to cause EOF.
6044 (In some old system, shutdown to socketpair doesn't work.
6045 Then we just can't win.) */
6046 if (EQ (XPROCESS (proc)->type, Qnetwork)
6047 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6048 shutdown (XPROCESS (proc)->outfd, 1);
6049 /* In case of socketpair, outfd == infd, so don't close it. */
6050 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6051 emacs_close (XPROCESS (proc)->outfd);
6052 #else /* not HAVE_SHUTDOWN */
6053 emacs_close (XPROCESS (proc)->outfd);
6054 #endif /* not HAVE_SHUTDOWN */
6055 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6056 if (new_outfd < 0)
6057 emacs_abort ();
6058 old_outfd = XPROCESS (proc)->outfd;
6059
6060 if (!proc_encode_coding_system[new_outfd])
6061 proc_encode_coding_system[new_outfd]
6062 = xmalloc (sizeof (struct coding_system));
6063 *proc_encode_coding_system[new_outfd]
6064 = *proc_encode_coding_system[old_outfd];
6065 memset (proc_encode_coding_system[old_outfd], 0,
6066 sizeof (struct coding_system));
6067
6068 XPROCESS (proc)->outfd = new_outfd;
6069 }
6070 return process;
6071 }
6072 \f
6073 /* The main Emacs thread records child processes in three places:
6074
6075 - Vprocess_alist, for asynchronous subprocesses, which are child
6076 processes visible to Lisp.
6077
6078 - deleted_pid_list, for child processes invisible to Lisp,
6079 typically because of delete-process. These are recorded so that
6080 the processes can be reaped when they exit, so that the operating
6081 system's process table is not cluttered by zombies.
6082
6083 - the local variable PID in Fcall_process, call_process_cleanup and
6084 call_process_kill, for synchronous subprocesses.
6085 record_unwind_protect is used to make sure this process is not
6086 forgotten: if the user interrupts call-process and the child
6087 process refuses to exit immediately even with two C-g's,
6088 call_process_kill adds PID's contents to deleted_pid_list before
6089 returning.
6090
6091 The main Emacs thread invokes waitpid only on child processes that
6092 it creates and that have not been reaped. This avoid races on
6093 platforms such as GTK, where other threads create their own
6094 subprocesses which the main thread should not reap. For example,
6095 if the main thread attempted to reap an already-reaped child, it
6096 might inadvertently reap a GTK-created process that happened to
6097 have the same process ID. */
6098
6099 /* Handle a SIGCHLD signal by looking for known child processes of
6100 Emacs whose status have changed. For each one found, record its
6101 new status.
6102
6103 All we do is change the status; we do not run sentinels or print
6104 notifications. That is saved for the next time keyboard input is
6105 done, in order to avoid timing errors.
6106
6107 ** WARNING: this can be called during garbage collection.
6108 Therefore, it must not be fooled by the presence of mark bits in
6109 Lisp objects.
6110
6111 ** USG WARNING: Although it is not obvious from the documentation
6112 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6113 signal() before executing at least one wait(), otherwise the
6114 handler will be called again, resulting in an infinite loop. The
6115 relevant portion of the documentation reads "SIGCLD signals will be
6116 queued and the signal-catching function will be continually
6117 reentered until the queue is empty". Invoking signal() causes the
6118 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6119 Inc.
6120
6121 ** Malloc WARNING: This should never call malloc either directly or
6122 indirectly; if it does, that is a bug */
6123
6124 static void
6125 handle_child_signal (int sig)
6126 {
6127 Lisp_Object tail;
6128
6129 /* Find the process that signaled us, and record its status. */
6130
6131 /* The process can have been deleted by Fdelete_process, or have
6132 been started asynchronously by Fcall_process. */
6133 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6134 {
6135 bool all_pids_are_fixnums
6136 = (MOST_NEGATIVE_FIXNUM <= TYPE_MINIMUM (pid_t)
6137 && TYPE_MAXIMUM (pid_t) <= MOST_POSITIVE_FIXNUM);
6138 Lisp_Object xpid = XCAR (tail);
6139 if (all_pids_are_fixnums ? INTEGERP (xpid) : NUMBERP (xpid))
6140 {
6141 pid_t deleted_pid;
6142 if (INTEGERP (xpid))
6143 deleted_pid = XINT (xpid);
6144 else
6145 deleted_pid = XFLOAT_DATA (xpid);
6146 if (child_status_changed (deleted_pid, 0, 0))
6147 XSETCAR (tail, Qnil);
6148 }
6149 }
6150
6151 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6152 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6153 {
6154 Lisp_Object proc = XCDR (XCAR (tail));
6155 struct Lisp_Process *p = XPROCESS (proc);
6156 int status;
6157
6158 if (p->alive && child_status_changed (p->pid, &status, WUNTRACED))
6159 {
6160 /* Change the status of the process that was found. */
6161 p->tick = ++process_tick;
6162 p->raw_status = status;
6163 p->raw_status_new = 1;
6164
6165 /* If process has terminated, stop waiting for its output. */
6166 if (WIFSIGNALED (status) || WIFEXITED (status))
6167 {
6168 int clear_desc_flag = 0;
6169 p->alive = 0;
6170 if (p->infd >= 0)
6171 clear_desc_flag = 1;
6172
6173 /* clear_desc_flag avoids a compiler bug in Microsoft C. */
6174 if (clear_desc_flag)
6175 {
6176 FD_CLR (p->infd, &input_wait_mask);
6177 FD_CLR (p->infd, &non_keyboard_wait_mask);
6178 }
6179 }
6180 }
6181 }
6182 }
6183
6184 static void
6185 deliver_child_signal (int sig)
6186 {
6187 deliver_process_signal (sig, handle_child_signal);
6188 }
6189 \f
6190
6191 static Lisp_Object
6192 exec_sentinel_unwind (Lisp_Object data)
6193 {
6194 pset_sentinel (XPROCESS (XCAR (data)), XCDR (data));
6195 return Qnil;
6196 }
6197
6198 static Lisp_Object
6199 exec_sentinel_error_handler (Lisp_Object error_val)
6200 {
6201 cmd_error_internal (error_val, "error in process sentinel: ");
6202 Vinhibit_quit = Qt;
6203 update_echo_area ();
6204 Fsleep_for (make_number (2), Qnil);
6205 return Qt;
6206 }
6207
6208 static void
6209 exec_sentinel (Lisp_Object proc, Lisp_Object reason)
6210 {
6211 Lisp_Object sentinel, odeactivate;
6212 struct Lisp_Process *p = XPROCESS (proc);
6213 ptrdiff_t count = SPECPDL_INDEX ();
6214 bool outer_running_asynch_code = running_asynch_code;
6215 int waiting = waiting_for_user_input_p;
6216
6217 if (inhibit_sentinels)
6218 return;
6219
6220 /* No need to gcpro these, because all we do with them later
6221 is test them for EQness, and none of them should be a string. */
6222 odeactivate = Vdeactivate_mark;
6223 #if 0
6224 Lisp_Object obuffer, okeymap;
6225 XSETBUFFER (obuffer, current_buffer);
6226 okeymap = BVAR (current_buffer, keymap);
6227 #endif
6228
6229 /* There's no good reason to let sentinels change the current
6230 buffer, and many callers of accept-process-output, sit-for, and
6231 friends don't expect current-buffer to be changed from under them. */
6232 record_unwind_current_buffer ();
6233
6234 sentinel = p->sentinel;
6235 if (NILP (sentinel))
6236 return;
6237
6238 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6239 assure that it gets restored no matter how the sentinel exits. */
6240 pset_sentinel (p, Qnil);
6241 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6242 /* Inhibit quit so that random quits don't screw up a running filter. */
6243 specbind (Qinhibit_quit, Qt);
6244 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6245
6246 /* In case we get recursively called,
6247 and we already saved the match data nonrecursively,
6248 save the same match data in safely recursive fashion. */
6249 if (outer_running_asynch_code)
6250 {
6251 Lisp_Object tem;
6252 tem = Fmatch_data (Qnil, Qnil, Qnil);
6253 restore_search_regs ();
6254 record_unwind_save_match_data ();
6255 Fset_match_data (tem, Qt);
6256 }
6257
6258 /* For speed, if a search happens within this code,
6259 save the match data in a special nonrecursive fashion. */
6260 running_asynch_code = 1;
6261
6262 internal_condition_case_1 (read_process_output_call,
6263 Fcons (sentinel,
6264 Fcons (proc, Fcons (reason, Qnil))),
6265 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6266 exec_sentinel_error_handler);
6267
6268 /* If we saved the match data nonrecursively, restore it now. */
6269 restore_search_regs ();
6270 running_asynch_code = outer_running_asynch_code;
6271
6272 Vdeactivate_mark = odeactivate;
6273
6274 /* Restore waiting_for_user_input_p as it was
6275 when we were called, in case the filter clobbered it. */
6276 waiting_for_user_input_p = waiting;
6277
6278 #if 0
6279 if (! EQ (Fcurrent_buffer (), obuffer)
6280 || ! EQ (current_buffer->keymap, okeymap))
6281 #endif
6282 /* But do it only if the caller is actually going to read events.
6283 Otherwise there's no need to make him wake up, and it could
6284 cause trouble (for example it would make sit_for return). */
6285 if (waiting_for_user_input_p == -1)
6286 record_asynch_buffer_change ();
6287
6288 unbind_to (count, Qnil);
6289 }
6290
6291 /* Report all recent events of a change in process status
6292 (either run the sentinel or output a message).
6293 This is usually done while Emacs is waiting for keyboard input
6294 but can be done at other times. */
6295
6296 static void
6297 status_notify (struct Lisp_Process *deleting_process)
6298 {
6299 register Lisp_Object proc, buffer;
6300 Lisp_Object tail, msg;
6301 struct gcpro gcpro1, gcpro2;
6302
6303 tail = Qnil;
6304 msg = Qnil;
6305 /* We need to gcpro tail; if read_process_output calls a filter
6306 which deletes a process and removes the cons to which tail points
6307 from Vprocess_alist, and then causes a GC, tail is an unprotected
6308 reference. */
6309 GCPRO2 (tail, msg);
6310
6311 /* Set this now, so that if new processes are created by sentinels
6312 that we run, we get called again to handle their status changes. */
6313 update_tick = process_tick;
6314
6315 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6316 {
6317 Lisp_Object symbol;
6318 register struct Lisp_Process *p;
6319
6320 proc = Fcdr (XCAR (tail));
6321 p = XPROCESS (proc);
6322
6323 if (p->tick != p->update_tick)
6324 {
6325 p->update_tick = p->tick;
6326
6327 /* If process is still active, read any output that remains. */
6328 while (! EQ (p->filter, Qt)
6329 && ! EQ (p->status, Qconnect)
6330 && ! EQ (p->status, Qlisten)
6331 /* Network or serial process not stopped: */
6332 && ! EQ (p->command, Qt)
6333 && p->infd >= 0
6334 && p != deleting_process
6335 && read_process_output (proc, p->infd) > 0);
6336
6337 buffer = p->buffer;
6338
6339 /* Get the text to use for the message. */
6340 if (p->raw_status_new)
6341 update_status (p);
6342 msg = status_message (p);
6343
6344 /* If process is terminated, deactivate it or delete it. */
6345 symbol = p->status;
6346 if (CONSP (p->status))
6347 symbol = XCAR (p->status);
6348
6349 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6350 || EQ (symbol, Qclosed))
6351 {
6352 if (delete_exited_processes)
6353 remove_process (proc);
6354 else
6355 deactivate_process (proc);
6356 }
6357
6358 /* The actions above may have further incremented p->tick.
6359 So set p->update_tick again
6360 so that an error in the sentinel will not cause
6361 this code to be run again. */
6362 p->update_tick = p->tick;
6363 /* Now output the message suitably. */
6364 if (!NILP (p->sentinel))
6365 exec_sentinel (proc, msg);
6366 /* Don't bother with a message in the buffer
6367 when a process becomes runnable. */
6368 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6369 {
6370 Lisp_Object tem;
6371 struct buffer *old = current_buffer;
6372 ptrdiff_t opoint, opoint_byte;
6373 ptrdiff_t before, before_byte;
6374
6375 /* Avoid error if buffer is deleted
6376 (probably that's why the process is dead, too) */
6377 if (!BUFFER_LIVE_P (XBUFFER (buffer)))
6378 continue;
6379 Fset_buffer (buffer);
6380
6381 opoint = PT;
6382 opoint_byte = PT_BYTE;
6383 /* Insert new output into buffer
6384 at the current end-of-output marker,
6385 thus preserving logical ordering of input and output. */
6386 if (XMARKER (p->mark)->buffer)
6387 Fgoto_char (p->mark);
6388 else
6389 SET_PT_BOTH (ZV, ZV_BYTE);
6390
6391 before = PT;
6392 before_byte = PT_BYTE;
6393
6394 tem = BVAR (current_buffer, read_only);
6395 bset_read_only (current_buffer, Qnil);
6396 insert_string ("\nProcess ");
6397 { /* FIXME: temporary kludge */
6398 Lisp_Object tem2 = p->name; Finsert (1, &tem2); }
6399 insert_string (" ");
6400 Finsert (1, &msg);
6401 bset_read_only (current_buffer, tem);
6402 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6403
6404 if (opoint >= before)
6405 SET_PT_BOTH (opoint + (PT - before),
6406 opoint_byte + (PT_BYTE - before_byte));
6407 else
6408 SET_PT_BOTH (opoint, opoint_byte);
6409
6410 set_buffer_internal (old);
6411 }
6412 }
6413 } /* end for */
6414
6415 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6416 UNGCPRO;
6417 }
6418
6419 \f
6420 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6421 Sset_process_coding_system, 1, 3, 0,
6422 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6423 DECODING will be used to decode subprocess output and ENCODING to
6424 encode subprocess input. */)
6425 (register Lisp_Object process, Lisp_Object decoding, Lisp_Object encoding)
6426 {
6427 register struct Lisp_Process *p;
6428
6429 CHECK_PROCESS (process);
6430 p = XPROCESS (process);
6431 if (p->infd < 0)
6432 error ("Input file descriptor of %s closed", SDATA (p->name));
6433 if (p->outfd < 0)
6434 error ("Output file descriptor of %s closed", SDATA (p->name));
6435 Fcheck_coding_system (decoding);
6436 Fcheck_coding_system (encoding);
6437 encoding = coding_inherit_eol_type (encoding, Qnil);
6438 pset_decode_coding_system (p, decoding);
6439 pset_encode_coding_system (p, encoding);
6440 setup_process_coding_systems (process);
6441
6442 return Qnil;
6443 }
6444
6445 DEFUN ("process-coding-system",
6446 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6447 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6448 (register Lisp_Object process)
6449 {
6450 CHECK_PROCESS (process);
6451 return Fcons (XPROCESS (process)->decode_coding_system,
6452 XPROCESS (process)->encode_coding_system);
6453 }
6454
6455 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6456 Sset_process_filter_multibyte, 2, 2, 0,
6457 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6458 If FLAG is non-nil, the filter is given multibyte strings.
6459 If FLAG is nil, the filter is given unibyte strings. In this case,
6460 all character code conversion except for end-of-line conversion is
6461 suppressed. */)
6462 (Lisp_Object process, Lisp_Object flag)
6463 {
6464 register struct Lisp_Process *p;
6465
6466 CHECK_PROCESS (process);
6467 p = XPROCESS (process);
6468 if (NILP (flag))
6469 pset_decode_coding_system
6470 (p, raw_text_coding_system (p->decode_coding_system));
6471 setup_process_coding_systems (process);
6472
6473 return Qnil;
6474 }
6475
6476 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6477 Sprocess_filter_multibyte_p, 1, 1, 0,
6478 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6479 (Lisp_Object process)
6480 {
6481 register struct Lisp_Process *p;
6482 struct coding_system *coding;
6483
6484 CHECK_PROCESS (process);
6485 p = XPROCESS (process);
6486 coding = proc_decode_coding_system[p->infd];
6487 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
6488 }
6489
6490
6491 \f
6492
6493 # ifdef HAVE_GPM
6494
6495 void
6496 add_gpm_wait_descriptor (int desc)
6497 {
6498 add_keyboard_wait_descriptor (desc);
6499 }
6500
6501 void
6502 delete_gpm_wait_descriptor (int desc)
6503 {
6504 delete_keyboard_wait_descriptor (desc);
6505 }
6506
6507 # endif
6508
6509 # ifdef USABLE_SIGIO
6510
6511 /* Return nonzero if *MASK has a bit set
6512 that corresponds to one of the keyboard input descriptors. */
6513
6514 static int
6515 keyboard_bit_set (fd_set *mask)
6516 {
6517 int fd;
6518
6519 for (fd = 0; fd <= max_input_desc; fd++)
6520 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6521 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6522 return 1;
6523
6524 return 0;
6525 }
6526 # endif
6527
6528 #else /* not subprocesses */
6529
6530 /* Defined on msdos.c. */
6531 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
6532 EMACS_TIME *, void *);
6533
6534 /* Implementation of wait_reading_process_output, assuming that there
6535 are no subprocesses. Used only by the MS-DOS build.
6536
6537 Wait for timeout to elapse and/or keyboard input to be available.
6538
6539 TIME_LIMIT is:
6540 timeout in seconds
6541 If negative, gobble data immediately available but don't wait for any.
6542
6543 NSECS is:
6544 an additional duration to wait, measured in nanoseconds
6545 If TIME_LIMIT is zero, then:
6546 If NSECS == 0, there is no limit.
6547 If NSECS > 0, the timeout consists of NSECS only.
6548 If NSECS < 0, gobble data immediately, as if TIME_LIMIT were negative.
6549
6550 READ_KBD is:
6551 0 to ignore keyboard input, or
6552 1 to return when input is available, or
6553 -1 means caller will actually read the input, so don't throw to
6554 the quit handler.
6555
6556 see full version for other parameters. We know that wait_proc will
6557 always be NULL, since `subprocesses' isn't defined.
6558
6559 DO_DISPLAY means redisplay should be done to show subprocess
6560 output that arrives.
6561
6562 Return true if we received input from any process. */
6563
6564 int
6565 wait_reading_process_output (intmax_t time_limit, int nsecs, int read_kbd,
6566 bool do_display,
6567 Lisp_Object wait_for_cell,
6568 struct Lisp_Process *wait_proc, int just_wait_proc)
6569 {
6570 register int nfds;
6571 EMACS_TIME end_time, timeout;
6572
6573 if (time_limit < 0)
6574 {
6575 time_limit = 0;
6576 nsecs = -1;
6577 }
6578 else if (TYPE_MAXIMUM (time_t) < time_limit)
6579 time_limit = TYPE_MAXIMUM (time_t);
6580
6581 /* What does time_limit really mean? */
6582 if (time_limit || 0 < nsecs)
6583 {
6584 timeout = make_emacs_time (time_limit, nsecs);
6585 end_time = add_emacs_time (current_emacs_time (), timeout);
6586 }
6587
6588 /* Turn off periodic alarms (in case they are in use)
6589 and then turn off any other atimers,
6590 because the select emulator uses alarms. */
6591 stop_polling ();
6592 turn_on_atimers (0);
6593
6594 while (1)
6595 {
6596 int timeout_reduced_for_timers = 0;
6597 SELECT_TYPE waitchannels;
6598 int xerrno;
6599
6600 /* If calling from keyboard input, do not quit
6601 since we want to return C-g as an input character.
6602 Otherwise, do pending quit if requested. */
6603 if (read_kbd >= 0)
6604 QUIT;
6605
6606 /* Exit now if the cell we're waiting for became non-nil. */
6607 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6608 break;
6609
6610 /* Compute time from now till when time limit is up */
6611 /* Exit if already run out */
6612 if (nsecs < 0)
6613 {
6614 /* A negative timeout means
6615 gobble output available now
6616 but don't wait at all. */
6617
6618 timeout = make_emacs_time (0, 0);
6619 }
6620 else if (time_limit || 0 < nsecs)
6621 {
6622 EMACS_TIME now = current_emacs_time ();
6623 if (EMACS_TIME_LE (end_time, now))
6624 break;
6625 timeout = sub_emacs_time (end_time, now);
6626 }
6627 else
6628 {
6629 timeout = make_emacs_time (100000, 0);
6630 }
6631
6632 /* If our caller will not immediately handle keyboard events,
6633 run timer events directly.
6634 (Callers that will immediately read keyboard events
6635 call timer_delay on their own.) */
6636 if (NILP (wait_for_cell))
6637 {
6638 EMACS_TIME timer_delay;
6639
6640 do
6641 {
6642 unsigned old_timers_run = timers_run;
6643 timer_delay = timer_check ();
6644 if (timers_run != old_timers_run && do_display)
6645 /* We must retry, since a timer may have requeued itself
6646 and that could alter the time delay. */
6647 redisplay_preserve_echo_area (14);
6648 else
6649 break;
6650 }
6651 while (!detect_input_pending ());
6652
6653 /* If there is unread keyboard input, also return. */
6654 if (read_kbd != 0
6655 && requeued_events_pending_p ())
6656 break;
6657
6658 if (EMACS_TIME_VALID_P (timer_delay) && 0 <= nsecs)
6659 {
6660 if (EMACS_TIME_LT (timer_delay, timeout))
6661 {
6662 timeout = timer_delay;
6663 timeout_reduced_for_timers = 1;
6664 }
6665 }
6666 }
6667
6668 /* Cause C-g and alarm signals to take immediate action,
6669 and cause input available signals to zero out timeout. */
6670 if (read_kbd < 0)
6671 set_waiting_for_input (&timeout);
6672
6673 /* If a frame has been newly mapped and needs updating,
6674 reprocess its display stuff. */
6675 if (frame_garbaged && do_display)
6676 {
6677 clear_waiting_for_input ();
6678 redisplay_preserve_echo_area (15);
6679 if (read_kbd < 0)
6680 set_waiting_for_input (&timeout);
6681 }
6682
6683 /* Wait till there is something to do. */
6684 FD_ZERO (&waitchannels);
6685 if (read_kbd && detect_input_pending ())
6686 nfds = 0;
6687 else
6688 {
6689 if (read_kbd || !NILP (wait_for_cell))
6690 FD_SET (0, &waitchannels);
6691 nfds = pselect (1, &waitchannels, NULL, NULL, &timeout, NULL);
6692 }
6693
6694 xerrno = errno;
6695
6696 /* Make C-g and alarm signals set flags again */
6697 clear_waiting_for_input ();
6698
6699 /* If we woke up due to SIGWINCH, actually change size now. */
6700 do_pending_window_change (0);
6701
6702 if ((time_limit || nsecs) && nfds == 0 && ! timeout_reduced_for_timers)
6703 /* We waited the full specified time, so return now. */
6704 break;
6705
6706 if (nfds == -1)
6707 {
6708 /* If the system call was interrupted, then go around the
6709 loop again. */
6710 if (xerrno == EINTR)
6711 FD_ZERO (&waitchannels);
6712 else
6713 error ("select error: %s", emacs_strerror (xerrno));
6714 }
6715
6716 /* Check for keyboard input */
6717
6718 if (read_kbd
6719 && detect_input_pending_run_timers (do_display))
6720 {
6721 swallow_events (do_display);
6722 if (detect_input_pending_run_timers (do_display))
6723 break;
6724 }
6725
6726 /* If there is unread keyboard input, also return. */
6727 if (read_kbd
6728 && requeued_events_pending_p ())
6729 break;
6730
6731 /* If wait_for_cell. check for keyboard input
6732 but don't run any timers.
6733 ??? (It seems wrong to me to check for keyboard
6734 input at all when wait_for_cell, but the code
6735 has been this way since July 1994.
6736 Try changing this after version 19.31.) */
6737 if (! NILP (wait_for_cell)
6738 && detect_input_pending ())
6739 {
6740 swallow_events (do_display);
6741 if (detect_input_pending ())
6742 break;
6743 }
6744
6745 /* Exit now if the cell we're waiting for became non-nil. */
6746 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6747 break;
6748 }
6749
6750 start_polling ();
6751
6752 return 0;
6753 }
6754
6755 #endif /* not subprocesses */
6756
6757 /* The following functions are needed even if async subprocesses are
6758 not supported. Some of them are no-op stubs in that case. */
6759
6760 /* Add DESC to the set of keyboard input descriptors. */
6761
6762 void
6763 add_keyboard_wait_descriptor (int desc)
6764 {
6765 #ifdef subprocesses /* actually means "not MSDOS" */
6766 FD_SET (desc, &input_wait_mask);
6767 FD_SET (desc, &non_process_wait_mask);
6768 if (desc > max_input_desc)
6769 max_input_desc = desc;
6770 #endif
6771 }
6772
6773 /* From now on, do not expect DESC to give keyboard input. */
6774
6775 void
6776 delete_keyboard_wait_descriptor (int desc)
6777 {
6778 #ifdef subprocesses
6779 int fd;
6780 int lim = max_input_desc;
6781
6782 FD_CLR (desc, &input_wait_mask);
6783 FD_CLR (desc, &non_process_wait_mask);
6784
6785 if (desc == max_input_desc)
6786 for (fd = 0; fd < lim; fd++)
6787 if (FD_ISSET (fd, &input_wait_mask) || FD_ISSET (fd, &write_mask))
6788 max_input_desc = fd;
6789 #endif
6790 }
6791
6792 /* Setup coding systems of PROCESS. */
6793
6794 void
6795 setup_process_coding_systems (Lisp_Object process)
6796 {
6797 #ifdef subprocesses
6798 struct Lisp_Process *p = XPROCESS (process);
6799 int inch = p->infd;
6800 int outch = p->outfd;
6801 Lisp_Object coding_system;
6802
6803 if (inch < 0 || outch < 0)
6804 return;
6805
6806 if (!proc_decode_coding_system[inch])
6807 proc_decode_coding_system[inch] = xmalloc (sizeof (struct coding_system));
6808 coding_system = p->decode_coding_system;
6809 if (! NILP (p->filter))
6810 ;
6811 else if (BUFFERP (p->buffer))
6812 {
6813 if (NILP (BVAR (XBUFFER (p->buffer), enable_multibyte_characters)))
6814 coding_system = raw_text_coding_system (coding_system);
6815 }
6816 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
6817
6818 if (!proc_encode_coding_system[outch])
6819 proc_encode_coding_system[outch] = xmalloc (sizeof (struct coding_system));
6820 setup_coding_system (p->encode_coding_system,
6821 proc_encode_coding_system[outch]);
6822 #endif
6823 }
6824
6825 /* Close all descriptors currently in use for communication
6826 with subprocess. This is used in a newly-forked subprocess
6827 to get rid of irrelevant descriptors. */
6828
6829 void
6830 close_process_descs (void)
6831 {
6832 #ifndef DOS_NT
6833 int i;
6834 for (i = 0; i < MAXDESC; i++)
6835 {
6836 Lisp_Object process;
6837 process = chan_process[i];
6838 if (!NILP (process))
6839 {
6840 int in = XPROCESS (process)->infd;
6841 int out = XPROCESS (process)->outfd;
6842 if (in >= 0)
6843 emacs_close (in);
6844 if (out >= 0 && in != out)
6845 emacs_close (out);
6846 }
6847 }
6848 #endif
6849 }
6850
6851 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6852 doc: /* Return the (or a) process associated with BUFFER.
6853 BUFFER may be a buffer or the name of one. */)
6854 (register Lisp_Object buffer)
6855 {
6856 #ifdef subprocesses
6857 register Lisp_Object buf, tail, proc;
6858
6859 if (NILP (buffer)) return Qnil;
6860 buf = Fget_buffer (buffer);
6861 if (NILP (buf)) return Qnil;
6862
6863 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6864 {
6865 proc = Fcdr (XCAR (tail));
6866 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
6867 return proc;
6868 }
6869 #endif /* subprocesses */
6870 return Qnil;
6871 }
6872
6873 DEFUN ("process-inherit-coding-system-flag",
6874 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6875 1, 1, 0,
6876 doc: /* Return the value of inherit-coding-system flag for PROCESS.
6877 If this flag is t, `buffer-file-coding-system' of the buffer
6878 associated with PROCESS will inherit the coding system used to decode
6879 the process output. */)
6880 (register Lisp_Object process)
6881 {
6882 #ifdef subprocesses
6883 CHECK_PROCESS (process);
6884 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
6885 #else
6886 /* Ignore the argument and return the value of
6887 inherit-process-coding-system. */
6888 return inherit_process_coding_system ? Qt : Qnil;
6889 #endif
6890 }
6891
6892 /* Kill all processes associated with `buffer'.
6893 If `buffer' is nil, kill all processes */
6894
6895 void
6896 kill_buffer_processes (Lisp_Object buffer)
6897 {
6898 #ifdef subprocesses
6899 Lisp_Object tail, proc;
6900
6901 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6902 {
6903 proc = XCDR (XCAR (tail));
6904 if (PROCESSP (proc)
6905 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6906 {
6907 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6908 Fdelete_process (proc);
6909 else if (XPROCESS (proc)->infd >= 0)
6910 process_send_signal (proc, SIGHUP, Qnil, 1);
6911 }
6912 }
6913 #else /* subprocesses */
6914 /* Since we have no subprocesses, this does nothing. */
6915 #endif /* subprocesses */
6916 }
6917
6918 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p,
6919 Swaiting_for_user_input_p, 0, 0, 0,
6920 doc: /* Returns non-nil if Emacs is waiting for input from the user.
6921 This is intended for use by asynchronous process output filters and sentinels. */)
6922 (void)
6923 {
6924 #ifdef subprocesses
6925 return (waiting_for_user_input_p ? Qt : Qnil);
6926 #else
6927 return Qnil;
6928 #endif
6929 }
6930
6931 /* Stop reading input from keyboard sources. */
6932
6933 void
6934 hold_keyboard_input (void)
6935 {
6936 kbd_is_on_hold = 1;
6937 }
6938
6939 /* Resume reading input from keyboard sources. */
6940
6941 void
6942 unhold_keyboard_input (void)
6943 {
6944 kbd_is_on_hold = 0;
6945 }
6946
6947 /* Return non-zero if keyboard input is on hold, zero otherwise. */
6948
6949 int
6950 kbd_on_hold_p (void)
6951 {
6952 return kbd_is_on_hold;
6953 }
6954
6955 \f
6956 /* Enumeration of and access to system processes a-la ps(1). */
6957
6958 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
6959 0, 0, 0,
6960 doc: /* Return a list of numerical process IDs of all running processes.
6961 If this functionality is unsupported, return nil.
6962
6963 See `process-attributes' for getting attributes of a process given its ID. */)
6964 (void)
6965 {
6966 return list_system_processes ();
6967 }
6968
6969 DEFUN ("process-attributes", Fprocess_attributes,
6970 Sprocess_attributes, 1, 1, 0,
6971 doc: /* Return attributes of the process given by its PID, a number.
6972
6973 Value is an alist where each element is a cons cell of the form
6974
6975 \(KEY . VALUE)
6976
6977 If this functionality is unsupported, the value is nil.
6978
6979 See `list-system-processes' for getting a list of all process IDs.
6980
6981 The KEYs of the attributes that this function may return are listed
6982 below, together with the type of the associated VALUE (in parentheses).
6983 Not all platforms support all of these attributes; unsupported
6984 attributes will not appear in the returned alist.
6985 Unless explicitly indicated otherwise, numbers can have either
6986 integer or floating point values.
6987
6988 euid -- Effective user User ID of the process (number)
6989 user -- User name corresponding to euid (string)
6990 egid -- Effective user Group ID of the process (number)
6991 group -- Group name corresponding to egid (string)
6992 comm -- Command name (executable name only) (string)
6993 state -- Process state code, such as "S", "R", or "T" (string)
6994 ppid -- Parent process ID (number)
6995 pgrp -- Process group ID (number)
6996 sess -- Session ID, i.e. process ID of session leader (number)
6997 ttname -- Controlling tty name (string)
6998 tpgid -- ID of foreground process group on the process's tty (number)
6999 minflt -- number of minor page faults (number)
7000 majflt -- number of major page faults (number)
7001 cminflt -- cumulative number of minor page faults (number)
7002 cmajflt -- cumulative number of major page faults (number)
7003 utime -- user time used by the process, in (current-time) format,
7004 which is a list of integers (HIGH LOW USEC PSEC)
7005 stime -- system time used by the process (current-time)
7006 time -- sum of utime and stime (current-time)
7007 cutime -- user time used by the process and its children (current-time)
7008 cstime -- system time used by the process and its children (current-time)
7009 ctime -- sum of cutime and cstime (current-time)
7010 pri -- priority of the process (number)
7011 nice -- nice value of the process (number)
7012 thcount -- process thread count (number)
7013 start -- time the process started (current-time)
7014 vsize -- virtual memory size of the process in KB's (number)
7015 rss -- resident set size of the process in KB's (number)
7016 etime -- elapsed time the process is running, in (HIGH LOW USEC PSEC) format
7017 pcpu -- percents of CPU time used by the process (floating-point number)
7018 pmem -- percents of total physical memory used by process's resident set
7019 (floating-point number)
7020 args -- command line which invoked the process (string). */)
7021 ( Lisp_Object pid)
7022 {
7023 return system_process_attributes (pid);
7024 }
7025
7026 \f
7027 /* This is not called "init_process" because that is the name of a
7028 Mach system call, so it would cause problems on Darwin systems. */
7029 void
7030 init_process_emacs (void)
7031 {
7032 #ifdef subprocesses
7033 register int i;
7034
7035 inhibit_sentinels = 0;
7036
7037 #ifndef CANNOT_DUMP
7038 if (! noninteractive || initialized)
7039 #endif
7040 {
7041 struct sigaction action;
7042 emacs_sigaction_init (&action, deliver_child_signal);
7043 sigaction (SIGCHLD, &action, 0);
7044 }
7045
7046 FD_ZERO (&input_wait_mask);
7047 FD_ZERO (&non_keyboard_wait_mask);
7048 FD_ZERO (&non_process_wait_mask);
7049 FD_ZERO (&write_mask);
7050 max_process_desc = 0;
7051 memset (fd_callback_info, 0, sizeof (fd_callback_info));
7052
7053 #ifdef NON_BLOCKING_CONNECT
7054 FD_ZERO (&connect_wait_mask);
7055 num_pending_connects = 0;
7056 #endif
7057
7058 #ifdef ADAPTIVE_READ_BUFFERING
7059 process_output_delay_count = 0;
7060 process_output_skip = 0;
7061 #endif
7062
7063 /* Don't do this, it caused infinite select loops. The display
7064 method should call add_keyboard_wait_descriptor on stdin if it
7065 needs that. */
7066 #if 0
7067 FD_SET (0, &input_wait_mask);
7068 #endif
7069
7070 Vprocess_alist = Qnil;
7071 deleted_pid_list = Qnil;
7072 for (i = 0; i < MAXDESC; i++)
7073 {
7074 chan_process[i] = Qnil;
7075 proc_buffered_char[i] = -1;
7076 }
7077 memset (proc_decode_coding_system, 0, sizeof proc_decode_coding_system);
7078 memset (proc_encode_coding_system, 0, sizeof proc_encode_coding_system);
7079 #ifdef DATAGRAM_SOCKETS
7080 memset (datagram_address, 0, sizeof datagram_address);
7081 #endif
7082
7083 {
7084 Lisp_Object subfeatures = Qnil;
7085 const struct socket_options *sopt;
7086
7087 #define ADD_SUBFEATURE(key, val) \
7088 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7089
7090 #ifdef NON_BLOCKING_CONNECT
7091 ADD_SUBFEATURE (QCnowait, Qt);
7092 #endif
7093 #ifdef DATAGRAM_SOCKETS
7094 ADD_SUBFEATURE (QCtype, Qdatagram);
7095 #endif
7096 #ifdef HAVE_SEQPACKET
7097 ADD_SUBFEATURE (QCtype, Qseqpacket);
7098 #endif
7099 #ifdef HAVE_LOCAL_SOCKETS
7100 ADD_SUBFEATURE (QCfamily, Qlocal);
7101 #endif
7102 ADD_SUBFEATURE (QCfamily, Qipv4);
7103 #ifdef AF_INET6
7104 ADD_SUBFEATURE (QCfamily, Qipv6);
7105 #endif
7106 #ifdef HAVE_GETSOCKNAME
7107 ADD_SUBFEATURE (QCservice, Qt);
7108 #endif
7109 ADD_SUBFEATURE (QCserver, Qt);
7110
7111 for (sopt = socket_options; sopt->name; sopt++)
7112 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7113
7114 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7115 }
7116
7117 #if defined (DARWIN_OS)
7118 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7119 processes. As such, we only change the default value. */
7120 if (initialized)
7121 {
7122 char const *release = (STRINGP (Voperating_system_release)
7123 ? SSDATA (Voperating_system_release)
7124 : 0);
7125 if (!release || !release[0] || (release[0] < '7' && release[1] == '.')) {
7126 Vprocess_connection_type = Qnil;
7127 }
7128 }
7129 #endif
7130 #endif /* subprocesses */
7131 kbd_is_on_hold = 0;
7132 }
7133
7134 void
7135 syms_of_process (void)
7136 {
7137 #ifdef subprocesses
7138
7139 DEFSYM (Qprocessp, "processp");
7140 DEFSYM (Qrun, "run");
7141 DEFSYM (Qstop, "stop");
7142 DEFSYM (Qsignal, "signal");
7143
7144 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7145 here again.
7146
7147 Qexit = intern_c_string ("exit");
7148 staticpro (&Qexit); */
7149
7150 DEFSYM (Qopen, "open");
7151 DEFSYM (Qclosed, "closed");
7152 DEFSYM (Qconnect, "connect");
7153 DEFSYM (Qfailed, "failed");
7154 DEFSYM (Qlisten, "listen");
7155 DEFSYM (Qlocal, "local");
7156 DEFSYM (Qipv4, "ipv4");
7157 #ifdef AF_INET6
7158 DEFSYM (Qipv6, "ipv6");
7159 #endif
7160 DEFSYM (Qdatagram, "datagram");
7161 DEFSYM (Qseqpacket, "seqpacket");
7162
7163 DEFSYM (QCport, ":port");
7164 DEFSYM (QCspeed, ":speed");
7165 DEFSYM (QCprocess, ":process");
7166
7167 DEFSYM (QCbytesize, ":bytesize");
7168 DEFSYM (QCstopbits, ":stopbits");
7169 DEFSYM (QCparity, ":parity");
7170 DEFSYM (Qodd, "odd");
7171 DEFSYM (Qeven, "even");
7172 DEFSYM (QCflowcontrol, ":flowcontrol");
7173 DEFSYM (Qhw, "hw");
7174 DEFSYM (Qsw, "sw");
7175 DEFSYM (QCsummary, ":summary");
7176
7177 DEFSYM (Qreal, "real");
7178 DEFSYM (Qnetwork, "network");
7179 DEFSYM (Qserial, "serial");
7180 DEFSYM (QCbuffer, ":buffer");
7181 DEFSYM (QChost, ":host");
7182 DEFSYM (QCservice, ":service");
7183 DEFSYM (QClocal, ":local");
7184 DEFSYM (QCremote, ":remote");
7185 DEFSYM (QCcoding, ":coding");
7186 DEFSYM (QCserver, ":server");
7187 DEFSYM (QCnowait, ":nowait");
7188 DEFSYM (QCsentinel, ":sentinel");
7189 DEFSYM (QClog, ":log");
7190 DEFSYM (QCnoquery, ":noquery");
7191 DEFSYM (QCstop, ":stop");
7192 DEFSYM (QCoptions, ":options");
7193 DEFSYM (QCplist, ":plist");
7194
7195 DEFSYM (Qlast_nonmenu_event, "last-nonmenu-event");
7196
7197 staticpro (&Vprocess_alist);
7198 staticpro (&deleted_pid_list);
7199
7200 #endif /* subprocesses */
7201
7202 DEFSYM (QCname, ":name");
7203 DEFSYM (QCtype, ":type");
7204
7205 DEFSYM (Qeuid, "euid");
7206 DEFSYM (Qegid, "egid");
7207 DEFSYM (Quser, "user");
7208 DEFSYM (Qgroup, "group");
7209 DEFSYM (Qcomm, "comm");
7210 DEFSYM (Qstate, "state");
7211 DEFSYM (Qppid, "ppid");
7212 DEFSYM (Qpgrp, "pgrp");
7213 DEFSYM (Qsess, "sess");
7214 DEFSYM (Qttname, "ttname");
7215 DEFSYM (Qtpgid, "tpgid");
7216 DEFSYM (Qminflt, "minflt");
7217 DEFSYM (Qmajflt, "majflt");
7218 DEFSYM (Qcminflt, "cminflt");
7219 DEFSYM (Qcmajflt, "cmajflt");
7220 DEFSYM (Qutime, "utime");
7221 DEFSYM (Qstime, "stime");
7222 DEFSYM (Qtime, "time");
7223 DEFSYM (Qcutime, "cutime");
7224 DEFSYM (Qcstime, "cstime");
7225 DEFSYM (Qctime, "ctime");
7226 DEFSYM (Qpri, "pri");
7227 DEFSYM (Qnice, "nice");
7228 DEFSYM (Qthcount, "thcount");
7229 DEFSYM (Qstart, "start");
7230 DEFSYM (Qvsize, "vsize");
7231 DEFSYM (Qrss, "rss");
7232 DEFSYM (Qetime, "etime");
7233 DEFSYM (Qpcpu, "pcpu");
7234 DEFSYM (Qpmem, "pmem");
7235 DEFSYM (Qargs, "args");
7236
7237 DEFVAR_BOOL ("delete-exited-processes", delete_exited_processes,
7238 doc: /* Non-nil means delete processes immediately when they exit.
7239 A value of nil means don't delete them until `list-processes' is run. */);
7240
7241 delete_exited_processes = 1;
7242
7243 #ifdef subprocesses
7244 DEFVAR_LISP ("process-connection-type", Vprocess_connection_type,
7245 doc: /* Control type of device used to communicate with subprocesses.
7246 Values are nil to use a pipe, or t or `pty' to use a pty.
7247 The value has no effect if the system has no ptys or if all ptys are busy:
7248 then a pipe is used in any case.
7249 The value takes effect when `start-process' is called. */);
7250 Vprocess_connection_type = Qt;
7251
7252 #ifdef ADAPTIVE_READ_BUFFERING
7253 DEFVAR_LISP ("process-adaptive-read-buffering", Vprocess_adaptive_read_buffering,
7254 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7255 On some systems, when Emacs reads the output from a subprocess, the output data
7256 is read in very small blocks, potentially resulting in very poor performance.
7257 This behavior can be remedied to some extent by setting this variable to a
7258 non-nil value, as it will automatically delay reading from such processes, to
7259 allow them to produce more output before Emacs tries to read it.
7260 If the value is t, the delay is reset after each write to the process; any other
7261 non-nil value means that the delay is not reset on write.
7262 The variable takes effect when `start-process' is called. */);
7263 Vprocess_adaptive_read_buffering = Qt;
7264 #endif
7265
7266 defsubr (&Sprocessp);
7267 defsubr (&Sget_process);
7268 defsubr (&Sdelete_process);
7269 defsubr (&Sprocess_status);
7270 defsubr (&Sprocess_exit_status);
7271 defsubr (&Sprocess_id);
7272 defsubr (&Sprocess_name);
7273 defsubr (&Sprocess_tty_name);
7274 defsubr (&Sprocess_command);
7275 defsubr (&Sset_process_buffer);
7276 defsubr (&Sprocess_buffer);
7277 defsubr (&Sprocess_mark);
7278 defsubr (&Sset_process_filter);
7279 defsubr (&Sprocess_filter);
7280 defsubr (&Sset_process_sentinel);
7281 defsubr (&Sprocess_sentinel);
7282 defsubr (&Sset_process_window_size);
7283 defsubr (&Sset_process_inherit_coding_system_flag);
7284 defsubr (&Sset_process_query_on_exit_flag);
7285 defsubr (&Sprocess_query_on_exit_flag);
7286 defsubr (&Sprocess_contact);
7287 defsubr (&Sprocess_plist);
7288 defsubr (&Sset_process_plist);
7289 defsubr (&Sprocess_list);
7290 defsubr (&Sstart_process);
7291 defsubr (&Sserial_process_configure);
7292 defsubr (&Smake_serial_process);
7293 defsubr (&Sset_network_process_option);
7294 defsubr (&Smake_network_process);
7295 defsubr (&Sformat_network_address);
7296 #if defined (HAVE_NET_IF_H)
7297 #ifdef SIOCGIFCONF
7298 defsubr (&Snetwork_interface_list);
7299 #endif
7300 #if defined (SIOCGIFADDR) || defined (SIOCGIFHWADDR) || defined (SIOCGIFFLAGS)
7301 defsubr (&Snetwork_interface_info);
7302 #endif
7303 #endif /* defined (HAVE_NET_IF_H) */
7304 #ifdef DATAGRAM_SOCKETS
7305 defsubr (&Sprocess_datagram_address);
7306 defsubr (&Sset_process_datagram_address);
7307 #endif
7308 defsubr (&Saccept_process_output);
7309 defsubr (&Sprocess_send_region);
7310 defsubr (&Sprocess_send_string);
7311 defsubr (&Sinterrupt_process);
7312 defsubr (&Skill_process);
7313 defsubr (&Squit_process);
7314 defsubr (&Sstop_process);
7315 defsubr (&Scontinue_process);
7316 defsubr (&Sprocess_running_child_p);
7317 defsubr (&Sprocess_send_eof);
7318 defsubr (&Ssignal_process);
7319 defsubr (&Swaiting_for_user_input_p);
7320 defsubr (&Sprocess_type);
7321 defsubr (&Sset_process_coding_system);
7322 defsubr (&Sprocess_coding_system);
7323 defsubr (&Sset_process_filter_multibyte);
7324 defsubr (&Sprocess_filter_multibyte_p);
7325
7326 #endif /* subprocesses */
7327
7328 defsubr (&Sget_buffer_process);
7329 defsubr (&Sprocess_inherit_coding_system_flag);
7330 defsubr (&Slist_system_processes);
7331 defsubr (&Sprocess_attributes);
7332 }