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