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