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