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