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