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