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