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