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