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