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