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