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