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