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