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