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