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