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