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