(Fformat_time_string): Move doc string outside DEFUN.
[bpt/emacs.git] / src / process.c
CommitLineData
d0d6b7c5 1/* Asynchronous subprocess control for GNU Emacs.
03832893
RS
2 Copyright (C) 1985, 86, 87, 88, 93, 94, 95, 1996
3 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
23#include <signal.h>
24
18160b98 25#include <config.h>
d0d6b7c5 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
e98d950b
RS
47#ifdef WINDOWSNT
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 */
d0d6b7c5
JB
60#endif /* HAVE_SOCKETS */
61
1d2c16fa
RS
62/* TERM is a poor-man's SLIP, used on Linux. */
63#ifdef TERM
64#include <client.h>
65#endif
66
cf32fea0
PR
67/* On some systems, e.g. DGUX, inet_addr returns a 'struct in_addr'. */
68#ifdef HAVE_BROKEN_INET_ADDR
79967d5e
RS
69#define IN_ADDR struct in_addr
70#define NUMERIC_ADDR_ERROR (numeric_addr.s_addr == -1)
71#else
72#define IN_ADDR unsigned long
73#define NUMERIC_ADDR_ERROR (numeric_addr == -1)
74#endif
75
6df54671 76#if defined(BSD_SYSTEM) || defined(STRIDE)
d0d6b7c5 77#include <sys/ioctl.h>
0ad77c54 78#if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
d0d6b7c5
JB
79#include <fcntl.h>
80#endif /* HAVE_PTYS and no O_NDELAY */
6df54671 81#endif /* BSD_SYSTEM || STRIDE */
d0d6b7c5 82
99e3d726
RS
83#ifdef BROKEN_O_NONBLOCK
84#undef O_NONBLOCK
85#endif /* BROKEN_O_NONBLOCK */
86
d0d6b7c5
JB
87#ifdef NEED_BSDTTY
88#include <bsdtty.h>
89#endif
90
d0d6b7c5
JB
91#ifdef IRIS
92#include <sys/sysmacros.h> /* for "minor" */
93#endif /* not IRIS */
94
95#include "systime.h"
36ebaafa 96#include "systty.h"
d0d6b7c5
JB
97
98#include "lisp.h"
99#include "window.h"
100#include "buffer.h"
0fa1789e
KH
101#include "charset.h"
102#include "coding.h"
d0d6b7c5
JB
103#include "process.h"
104#include "termhooks.h"
105#include "termopts.h"
106#include "commands.h"
1dc77cc3 107#include "frame.h"
ececcbec 108#include "blockinput.h"
d0d6b7c5 109
0c9960e9
RS
110#define max(a, b) ((a) > (b) ? (a) : (b))
111
dd2281ae 112Lisp_Object Qprocessp;
d0d6b7c5 113Lisp_Object Qrun, Qstop, Qsignal, Qopen, Qclosed;
6545aada 114Lisp_Object Qlast_nonmenu_event;
d0d6b7c5
JB
115/* Qexit is declared and initialized in eval.c. */
116
117/* a process object is a network connection when its childp field is neither
de282a05 118 Qt nor Qnil but is instead a cons cell (HOSTNAME PORTNUM). */
d0d6b7c5
JB
119
120#ifdef HAVE_SOCKETS
de282a05 121#define NETCONN_P(p) (GC_CONSP (XPROCESS (p)->childp))
d0d6b7c5
JB
122#else
123#define NETCONN_P(p) 0
124#endif /* HAVE_SOCKETS */
125
126/* Define first descriptor number available for subprocesses. */
127#ifdef VMS
128#define FIRST_PROC_DESC 1
129#else /* Not VMS */
130#define FIRST_PROC_DESC 3
131#endif
132
133/* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
134 testing SIGCHLD. */
135
136#if !defined (SIGCHLD) && defined (SIGCLD)
137#define SIGCHLD SIGCLD
138#endif /* SIGCLD */
139
140#include "syssignal.h"
141
889255b4 142#include "syswait.h"
d0d6b7c5 143
b062d1fe
RM
144extern int errno;
145extern char *strerror ();
146#ifdef VMS
d0d6b7c5 147extern char *sys_errlist[];
b062d1fe 148#endif
d0d6b7c5 149
5f0929a7
RS
150#ifndef HAVE_H_ERRNO
151extern int h_errno;
152#endif
153
a86928f7 154#ifndef SYS_SIGLIST_DECLARED
d0d6b7c5
JB
155#ifndef VMS
156#ifndef BSD4_1
e98d950b 157#ifndef WINDOWSNT
084fd64a 158#ifndef LINUX
d0d6b7c5 159extern char *sys_siglist[];
a0e4d3f3
RS
160#endif /* not LINUX */
161#else /* BSD4_1 */
d0d6b7c5
JB
162char *sys_siglist[] =
163 {
164 "bum signal!!",
165 "hangup",
166 "interrupt",
167 "quit",
168 "illegal instruction",
169 "trace trap",
170 "iot instruction",
171 "emt instruction",
172 "floating point exception",
173 "kill",
174 "bus error",
175 "segmentation violation",
176 "bad argument to system call",
177 "write on a pipe with no one to read it",
178 "alarm clock",
179 "software termination signal from kill",
180 "status signal",
181 "sendable stop signal not from tty",
182 "stop signal from tty",
183 "continue a stopped process",
184 "child status has changed",
185 "background read attempted from control tty",
186 "background write attempted from control tty",
187 "input record available at control tty",
188 "exceeded CPU time limit",
189 "exceeded file size limit"
190 };
e98d950b 191#endif /* not WINDOWSNT */
d0d6b7c5
JB
192#endif
193#endif /* VMS */
a86928f7 194#endif /* ! SYS_SIGLIST_DECLARED */
d0d6b7c5 195
d0d6b7c5
JB
196/* t means use pty, nil means use a pipe,
197 maybe other values to come. */
dd2281ae 198static Lisp_Object Vprocess_connection_type;
d0d6b7c5
JB
199
200#ifdef SKTPAIR
201#ifndef HAVE_SOCKETS
202#include <sys/socket.h>
203#endif
204#endif /* SKTPAIR */
205
17d02632
KH
206/* These next two vars are non-static since sysdep.c uses them in the
207 emulation of `select'. */
d0d6b7c5 208/* Number of events of change of status of a process. */
17d02632 209int process_tick;
d0d6b7c5 210/* Number of events for which the user or sentinel has been notified. */
17d02632 211int update_tick;
d0d6b7c5 212
5886acf9 213#include "sysselect.h"
d0d6b7c5 214
583dcae4 215/* If we support a window system, turn on the code to poll periodically
44ade2e9 216 to detect C-g. It isn't actually used when doing interrupt input. */
583dcae4 217#ifdef HAVE_WINDOW_SYSTEM
44ade2e9
RS
218#define POLL_FOR_INPUT
219#endif
220
a69281ff 221/* Mask of bits indicating the descriptors that we wait for input on. */
d0d6b7c5 222
dd2281ae
RS
223static SELECT_TYPE input_wait_mask;
224
a69281ff
RS
225/* Mask that excludes keyboard input descriptor (s). */
226
227static SELECT_TYPE non_keyboard_wait_mask;
228
b5dc1c83
RS
229/* Mask that excludes process input descriptor (s). */
230
231static SELECT_TYPE non_process_wait_mask;
232
7d0e672e
RS
233/* The largest descriptor currently in use for a process object. */
234static int max_process_desc;
235
a69281ff
RS
236/* The largest descriptor currently in use for keyboard input. */
237static int max_keyboard_desc;
d0d6b7c5 238
dd2281ae
RS
239/* Nonzero means delete a process right away if it exits. */
240static int delete_exited_processes;
d0d6b7c5
JB
241
242/* Indexed by descriptor, gives the process (if any) for that descriptor */
41f3aa98 243Lisp_Object chan_process[MAXDESC];
d0d6b7c5
JB
244
245/* Alist of elements (NAME . PROCESS) */
41f3aa98 246Lisp_Object Vprocess_alist;
d0d6b7c5
JB
247
248/* Buffered-ahead input char from process, indexed by channel.
249 -1 means empty (no char is buffered).
250 Used on sys V where the only way to tell if there is any
251 output from the process is to read at least one char.
252 Always -1 on systems that support FIONREAD. */
253
e98d950b
RS
254/* Don't make static; need to access externally. */
255int proc_buffered_char[MAXDESC];
dd2281ae 256
0fa1789e 257/* Table of `struct coding-system' for each process. */
c7580538
KH
258static struct coding_system *proc_decode_coding_system[MAXDESC];
259static struct coding_system *proc_encode_coding_system[MAXDESC];
0fa1789e 260
dd2281ae 261static Lisp_Object get_process ();
93b4f699 262
fb4c3627 263extern EMACS_TIME timer_check ();
5de50bfb 264extern int timers_run;
fb4c3627 265
93b4f699
RS
266/* Maximum number of bytes to send to a pty without an eof. */
267static int pty_max_bytes;
3b9a3dfa 268
875e6b94
KH
269#ifdef HAVE_PTYS
270/* The file name of the pty opened by allocate_pty. */
3b9a3dfa
RS
271
272static char pty_name[24];
875e6b94 273#endif
d0d6b7c5
JB
274\f
275/* Compute the Lisp form of the process status, p->status, from
276 the numeric status that was returned by `wait'. */
277
f9738840
JB
278Lisp_Object status_convert ();
279
d0d6b7c5
JB
280update_status (p)
281 struct Lisp_Process *p;
282{
283 union { int i; WAITTYPE wt; } u;
284 u.i = XFASTINT (p->raw_status_low) + (XFASTINT (p->raw_status_high) << 16);
285 p->status = status_convert (u.wt);
286 p->raw_status_low = Qnil;
287 p->raw_status_high = Qnil;
288}
289
91d10fa8 290/* Convert a process status word in Unix format to
d0d6b7c5
JB
291 the list that we use internally. */
292
293Lisp_Object
294status_convert (w)
295 WAITTYPE w;
296{
297 if (WIFSTOPPED (w))
298 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
299 else if (WIFEXITED (w))
300 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
301 WCOREDUMP (w) ? Qt : Qnil));
302 else if (WIFSIGNALED (w))
303 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
304 WCOREDUMP (w) ? Qt : Qnil));
305 else
306 return Qrun;
307}
308
309/* Given a status-list, extract the three pieces of information
310 and store them individually through the three pointers. */
311
312void
313decode_status (l, symbol, code, coredump)
314 Lisp_Object l;
315 Lisp_Object *symbol;
316 int *code;
317 int *coredump;
318{
319 Lisp_Object tem;
320
bcd69aea 321 if (SYMBOLP (l))
d0d6b7c5
JB
322 {
323 *symbol = l;
324 *code = 0;
325 *coredump = 0;
326 }
327 else
328 {
329 *symbol = XCONS (l)->car;
330 tem = XCONS (l)->cdr;
331 *code = XFASTINT (XCONS (tem)->car);
f9738840 332 tem = XCONS (tem)->cdr;
d0d6b7c5
JB
333 *coredump = !NILP (tem);
334 }
335}
336
337/* Return a string describing a process status list. */
338
339Lisp_Object
340status_message (status)
341 Lisp_Object status;
342{
343 Lisp_Object symbol;
344 int code, coredump;
345 Lisp_Object string, string2;
346
347 decode_status (status, &symbol, &code, &coredump);
348
349 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
350 {
b97ad9ea
RS
351 char *signame = 0;
352 if (code < NSIG)
353 {
b0310da4 354#ifndef VMS
ed0cae05
RS
355 /* Cast to suppress warning if the table has const char *. */
356 signame = (char *) sys_siglist[code];
b0310da4 357#else
b97ad9ea 358 signame = sys_errlist[code];
b0310da4 359#endif
b97ad9ea
RS
360 }
361 if (signame == 0)
362 signame = "unknown";
363 string = build_string (signame);
d0d6b7c5
JB
364 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
365 XSTRING (string)->data[0] = DOWNCASE (XSTRING (string)->data[0]);
366 return concat2 (string, string2);
367 }
368 else if (EQ (symbol, Qexit))
369 {
370 if (code == 0)
371 return build_string ("finished\n");
f2980264 372 string = Fnumber_to_string (make_number (code));
d0d6b7c5
JB
373 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
374 return concat2 (build_string ("exited abnormally with code "),
375 concat2 (string, string2));
376 }
377 else
378 return Fcopy_sequence (Fsymbol_name (symbol));
379}
380\f
381#ifdef HAVE_PTYS
d0d6b7c5 382
875e6b94
KH
383/* Open an available pty, returning a file descriptor.
384 Return -1 on failure.
385 The file name of the terminal corresponding to the pty
386 is left in the variable pty_name. */
387
d0d6b7c5
JB
388int
389allocate_pty ()
390{
391 struct stat stb;
392 register c, i;
393 int fd;
394
32676c08
JB
395 /* Some systems name their pseudoterminals so that there are gaps in
396 the usual sequence - for example, on HP9000/S700 systems, there
397 are no pseudoterminals with names ending in 'f'. So we wait for
398 three failures in a row before deciding that we've reached the
399 end of the ptys. */
400 int failed_count = 0;
401
d0d6b7c5
JB
402#ifdef PTY_ITERATION
403 PTY_ITERATION
404#else
405 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
406 for (i = 0; i < 16; i++)
407#endif
408 {
409#ifdef PTY_NAME_SPRINTF
410 PTY_NAME_SPRINTF
d0d6b7c5
JB
411#else
412 sprintf (pty_name, "/dev/pty%c%x", c, i);
d0d6b7c5
JB
413#endif /* no PTY_NAME_SPRINTF */
414
4d7c105e
RS
415#ifdef PTY_OPEN
416 PTY_OPEN;
417#else /* no PTY_OPEN */
32676c08
JB
418#ifdef IRIS
419 /* Unusual IRIS code */
420 *ptyv = open ("/dev/ptc", O_RDWR | O_NDELAY, 0);
421 if (fd < 0)
422 return -1;
423 if (fstat (fd, &stb) < 0)
d0d6b7c5 424 return -1;
4d7c105e 425#else /* not IRIS */
32676c08
JB
426 if (stat (pty_name, &stb) < 0)
427 {
428 failed_count++;
429 if (failed_count >= 3)
430 return -1;
431 }
432 else
433 failed_count = 0;
d0d6b7c5
JB
434#ifdef O_NONBLOCK
435 fd = open (pty_name, O_RDWR | O_NONBLOCK, 0);
436#else
437 fd = open (pty_name, O_RDWR | O_NDELAY, 0);
438#endif
4d7c105e
RS
439#endif /* not IRIS */
440#endif /* no PTY_OPEN */
d0d6b7c5
JB
441
442 if (fd >= 0)
443 {
444 /* check to make certain that both sides are available
445 this avoids a nasty yet stupid bug in rlogins */
446#ifdef PTY_TTY_NAME_SPRINTF
447 PTY_TTY_NAME_SPRINTF
d0d6b7c5
JB
448#else
449 sprintf (pty_name, "/dev/tty%c%x", c, i);
d0d6b7c5
JB
450#endif /* no PTY_TTY_NAME_SPRINTF */
451#ifndef UNIPLUS
452 if (access (pty_name, 6) != 0)
453 {
454 close (fd);
fad97cbe 455#if !defined(IRIS) && !defined(__sgi)
d0d6b7c5
JB
456 continue;
457#else
458 return -1;
459#endif /* IRIS */
460 }
461#endif /* not UNIPLUS */
462 setup_pty (fd);
463 return fd;
464 }
465 }
466 return -1;
467}
468#endif /* HAVE_PTYS */
469\f
470Lisp_Object
471make_process (name)
472 Lisp_Object name;
473{
23d6bb9c 474 struct Lisp_Vector *vec;
d0d6b7c5
JB
475 register Lisp_Object val, tem, name1;
476 register struct Lisp_Process *p;
477 char suffix[10];
478 register int i;
479
23d6bb9c
KH
480 vec = allocate_vectorlike ((EMACS_INT) VECSIZE (struct Lisp_Process));
481 for (i = 0; i < VECSIZE (struct Lisp_Process); i++)
482 vec->contents[i] = Qnil;
483 vec->size = VECSIZE (struct Lisp_Process);
484 p = (struct Lisp_Process *)vec;
485
1d056e64
KH
486 XSETINT (p->infd, -1);
487 XSETINT (p->outfd, -1);
22719df2
KH
488 XSETFASTINT (p->pid, 0);
489 XSETFASTINT (p->tick, 0);
490 XSETFASTINT (p->update_tick, 0);
d0d6b7c5
JB
491 p->raw_status_low = Qnil;
492 p->raw_status_high = Qnil;
493 p->status = Qrun;
494 p->mark = Fmake_marker ();
495
496 /* If name is already in use, modify it until it is unused. */
497
498 name1 = name;
499 for (i = 1; ; i++)
500 {
501 tem = Fget_process (name1);
502 if (NILP (tem)) break;
503 sprintf (suffix, "<%d>", i);
504 name1 = concat2 (name, build_string (suffix));
505 }
506 name = name1;
507 p->name = name;
23d6bb9c 508 XSETPROCESS (val, p);
d0d6b7c5
JB
509 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
510 return val;
511}
512
513remove_process (proc)
514 register Lisp_Object proc;
515{
516 register Lisp_Object pair;
517
518 pair = Frassq (proc, Vprocess_alist);
519 Vprocess_alist = Fdelq (pair, Vprocess_alist);
d0d6b7c5
JB
520
521 deactivate_process (proc);
522}
523\f
524DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
525 "Return t if OBJECT is a process.")
4ee3e309
EN
526 (object)
527 Lisp_Object object;
d0d6b7c5 528{
4ee3e309 529 return PROCESSP (object) ? Qt : Qnil;
d0d6b7c5
JB
530}
531
532DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
533 "Return the process named NAME, or nil if there is none.")
534 (name)
535 register Lisp_Object name;
536{
bcd69aea 537 if (PROCESSP (name))
d0d6b7c5
JB
538 return name;
539 CHECK_STRING (name, 0);
540 return Fcdr (Fassoc (name, Vprocess_alist));
541}
542
543DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
544 "Return the (or, a) process associated with BUFFER.\n\
545BUFFER may be a buffer or the name of one.")
4ee3e309
EN
546 (buffer)
547 register Lisp_Object buffer;
d0d6b7c5
JB
548{
549 register Lisp_Object buf, tail, proc;
550
4ee3e309
EN
551 if (NILP (buffer)) return Qnil;
552 buf = Fget_buffer (buffer);
d0d6b7c5
JB
553 if (NILP (buf)) return Qnil;
554
555 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
556 {
557 proc = Fcdr (Fcar (tail));
bcd69aea 558 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
d0d6b7c5
JB
559 return proc;
560 }
561 return Qnil;
562}
563
ebb9e16f
JB
564/* This is how commands for the user decode process arguments. It
565 accepts a process, a process name, a buffer, a buffer name, or nil.
566 Buffers denote the first process in the buffer, and nil denotes the
567 current buffer. */
d0d6b7c5 568
77b221b1 569static Lisp_Object
d0d6b7c5
JB
570get_process (name)
571 register Lisp_Object name;
572{
1619761d
KH
573 register Lisp_Object proc, obj;
574 if (STRINGP (name))
575 {
576 obj = Fget_process (name);
577 if (NILP (obj))
578 obj = Fget_buffer (name);
579 if (NILP (obj))
580 error ("Process %s does not exist", XSTRING (name)->data);
581 }
582 else if (NILP (name))
583 obj = Fcurrent_buffer ();
d0d6b7c5 584 else
1619761d
KH
585 obj = name;
586
587 /* Now obj should be either a buffer object or a process object.
588 */
589 if (BUFFERP (obj))
d0d6b7c5 590 {
1619761d 591 proc = Fget_buffer_process (obj);
d0d6b7c5 592 if (NILP (proc))
1619761d 593 error ("Buffer %s has no process", XSTRING (XBUFFER (obj)->name)->data);
d0d6b7c5 594 }
d0d6b7c5 595 else
1619761d
KH
596 {
597 CHECK_PROCESS (obj, 0);
598 proc = obj;
599 }
600 return proc;
d0d6b7c5
JB
601}
602
603DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
604 "Delete PROCESS: kill it and forget about it immediately.\n\
ebb9e16f
JB
605PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
606nil, indicating the current buffer's process.")
4ee3e309
EN
607 (process)
608 register Lisp_Object process;
d0d6b7c5 609{
4ee3e309
EN
610 process = get_process (process);
611 XPROCESS (process)->raw_status_low = Qnil;
612 XPROCESS (process)->raw_status_high = Qnil;
613 if (NETCONN_P (process))
d0d6b7c5 614 {
4ee3e309
EN
615 XPROCESS (process)->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
616 XSETINT (XPROCESS (process)->tick, ++process_tick);
d0d6b7c5 617 }
4ee3e309 618 else if (XINT (XPROCESS (process)->infd) >= 0)
d0d6b7c5 619 {
4ee3e309 620 Fkill_process (process, Qnil);
d0d6b7c5 621 /* Do this now, since remove_process will make sigchld_handler do nothing. */
4ee3e309 622 XPROCESS (process)->status
d0d6b7c5 623 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
4ee3e309 624 XSETINT (XPROCESS (process)->tick, ++process_tick);
d0d6b7c5
JB
625 status_notify ();
626 }
4ee3e309 627 remove_process (process);
d0d6b7c5
JB
628 return Qnil;
629}
630\f
631DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
632 "Return the status of PROCESS: a symbol, one of these:\n\
633run -- for a process that is running.\n\
634stop -- for a process stopped but continuable.\n\
635exit -- for a process that has exited.\n\
636signal -- for a process that has got a fatal signal.\n\
637open -- for a network stream connection that is open.\n\
638closed -- for a network stream connection that is closed.\n\
ebb9e16f
JB
639nil -- if arg is a process name and no such process exists.\n\
640PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
641nil, indicating the current buffer's process.")
4ee3e309
EN
642 (process)
643 register Lisp_Object process;
d0d6b7c5
JB
644{
645 register struct Lisp_Process *p;
646 register Lisp_Object status;
343f4114 647
4ee3e309
EN
648 if (STRINGP (process))
649 process = Fget_process (process);
343f4114 650 else
4ee3e309 651 process = get_process (process);
343f4114 652
4ee3e309
EN
653 if (NILP (process))
654 return process;
343f4114 655
4ee3e309 656 p = XPROCESS (process);
d0d6b7c5
JB
657 if (!NILP (p->raw_status_low))
658 update_status (p);
659 status = p->status;
bcd69aea 660 if (CONSP (status))
d0d6b7c5 661 status = XCONS (status)->car;
4ee3e309 662 if (NETCONN_P (process))
d0d6b7c5
JB
663 {
664 if (EQ (status, Qrun))
665 status = Qopen;
666 else if (EQ (status, Qexit))
667 status = Qclosed;
668 }
669 return status;
670}
671
672DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
673 1, 1, 0,
674 "Return the exit status of PROCESS or the signal number that killed it.\n\
675If PROCESS has not yet exited or died, return 0.")
4ee3e309
EN
676 (process)
677 register Lisp_Object process;
d0d6b7c5 678{
4ee3e309
EN
679 CHECK_PROCESS (process, 0);
680 if (!NILP (XPROCESS (process)->raw_status_low))
681 update_status (XPROCESS (process));
682 if (CONSP (XPROCESS (process)->status))
683 return XCONS (XCONS (XPROCESS (process)->status)->cdr)->car;
d0d6b7c5
JB
684 return make_number (0);
685}
686
687DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
688 "Return the process id of PROCESS.\n\
689This is the pid of the Unix process which PROCESS uses or talks to.\n\
690For a network connection, this value is nil.")
4ee3e309
EN
691 (process)
692 register Lisp_Object process;
d0d6b7c5 693{
4ee3e309
EN
694 CHECK_PROCESS (process, 0);
695 return XPROCESS (process)->pid;
d0d6b7c5
JB
696}
697
698DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
699 "Return the name of PROCESS, as a string.\n\
700This is the name of the program invoked in PROCESS,\n\
701possibly modified to make it unique among process names.")
4ee3e309
EN
702 (process)
703 register Lisp_Object process;
d0d6b7c5 704{
4ee3e309
EN
705 CHECK_PROCESS (process, 0);
706 return XPROCESS (process)->name;
d0d6b7c5
JB
707}
708
709DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
710 "Return the command that was executed to start PROCESS.\n\
711This is a list of strings, the first string being the program executed\n\
712and the rest of the strings being the arguments given to it.\n\
713For a non-child channel, this is nil.")
4ee3e309
EN
714 (process)
715 register Lisp_Object process;
d0d6b7c5 716{
4ee3e309
EN
717 CHECK_PROCESS (process, 0);
718 return XPROCESS (process)->command;
d0d6b7c5
JB
719}
720
3b9a3dfa
RS
721DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
722 "Return the name of the terminal PROCESS uses, or nil if none.\n\
723This is the terminal that the process itself reads and writes on,\n\
724not the name of the pty that Emacs uses to talk with that terminal.")
4ee3e309
EN
725 (process)
726 register Lisp_Object process;
3b9a3dfa 727{
4ee3e309
EN
728 CHECK_PROCESS (process, 0);
729 return XPROCESS (process)->tty_name;
3b9a3dfa
RS
730}
731
d0d6b7c5
JB
732DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
733 2, 2, 0,
734 "Set buffer associated with PROCESS to BUFFER (a buffer, or nil).")
4ee3e309
EN
735 (process, buffer)
736 register Lisp_Object process, buffer;
d0d6b7c5 737{
4ee3e309 738 CHECK_PROCESS (process, 0);
d0d6b7c5
JB
739 if (!NILP (buffer))
740 CHECK_BUFFER (buffer, 1);
4ee3e309 741 XPROCESS (process)->buffer = buffer;
d0d6b7c5
JB
742 return buffer;
743}
744
745DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
746 1, 1, 0,
747 "Return the buffer PROCESS is associated with.\n\
748Output from PROCESS is inserted in this buffer\n\
749unless PROCESS has a filter.")
4ee3e309
EN
750 (process)
751 register Lisp_Object process;
d0d6b7c5 752{
4ee3e309
EN
753 CHECK_PROCESS (process, 0);
754 return XPROCESS (process)->buffer;
d0d6b7c5
JB
755}
756
757DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
758 1, 1, 0,
759 "Return the marker for the end of the last output from PROCESS.")
4ee3e309
EN
760 (process)
761 register Lisp_Object process;
d0d6b7c5 762{
4ee3e309
EN
763 CHECK_PROCESS (process, 0);
764 return XPROCESS (process)->mark;
d0d6b7c5
JB
765}
766
767DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
768 2, 2, 0,
769 "Give PROCESS the filter function FILTER; nil means no filter.\n\
20ddfff7 770t means stop accepting output from the process.\n\
d0d6b7c5
JB
771When a process has a filter, each time it does output\n\
772the entire string of output is passed to the filter.\n\
773The filter gets two arguments: the process and the string of output.\n\
774If the process has a filter, its buffer is not used for output.")
4ee3e309
EN
775 (process, filter)
776 register Lisp_Object process, filter;
d0d6b7c5 777{
4ee3e309 778 CHECK_PROCESS (process, 0);
20ddfff7 779 if (EQ (filter, Qt))
a69281ff 780 {
4ee3e309
EN
781 FD_CLR (XINT (XPROCESS (process)->infd), &input_wait_mask);
782 FD_CLR (XINT (XPROCESS (process)->infd), &non_keyboard_wait_mask);
a69281ff 783 }
4ee3e309 784 else if (EQ (XPROCESS (process)->filter, Qt))
a69281ff 785 {
4ee3e309
EN
786 FD_SET (XINT (XPROCESS (process)->infd), &input_wait_mask);
787 FD_SET (XINT (XPROCESS (process)->infd), &non_keyboard_wait_mask);
a69281ff 788 }
4ee3e309 789 XPROCESS (process)->filter = filter;
d0d6b7c5
JB
790 return filter;
791}
792
793DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
794 1, 1, 0,
795 "Returns the filter function of PROCESS; nil if none.\n\
796See `set-process-filter' for more info on filter functions.")
4ee3e309
EN
797 (process)
798 register Lisp_Object process;
d0d6b7c5 799{
4ee3e309
EN
800 CHECK_PROCESS (process, 0);
801 return XPROCESS (process)->filter;
d0d6b7c5
JB
802}
803
804DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
805 2, 2, 0,
806 "Give PROCESS the sentinel SENTINEL; nil for none.\n\
807The sentinel is called as a function when the process changes state.\n\
808It gets two arguments: the process, and a string describing the change.")
4ee3e309
EN
809 (process, sentinel)
810 register Lisp_Object process, sentinel;
d0d6b7c5 811{
4ee3e309
EN
812 CHECK_PROCESS (process, 0);
813 XPROCESS (process)->sentinel = sentinel;
d0d6b7c5
JB
814 return sentinel;
815}
816
817DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
818 1, 1, 0,
819 "Return the sentinel of PROCESS; nil if none.\n\
820See `set-process-sentinel' for more info on sentinels.")
4ee3e309
EN
821 (process)
822 register Lisp_Object process;
d0d6b7c5 823{
4ee3e309
EN
824 CHECK_PROCESS (process, 0);
825 return XPROCESS (process)->sentinel;
d0d6b7c5
JB
826}
827
396df322
RS
828DEFUN ("set-process-window-size", Fset_process_window_size,
829 Sset_process_window_size, 3, 3, 0,
830 "Tell PROCESS that it has logical window size HEIGHT and WIDTH.")
4ee3e309
EN
831 (process, height, width)
832 register Lisp_Object process, height, width;
396df322 833{
4ee3e309 834 CHECK_PROCESS (process, 0);
396df322
RS
835 CHECK_NATNUM (height, 0);
836 CHECK_NATNUM (width, 0);
4ee3e309 837 if (set_window_size (XINT (XPROCESS (process)->infd),
396df322
RS
838 XINT (height), XINT(width)) <= 0)
839 return Qnil;
840 else
841 return Qt;
842}
843
d0d6b7c5
JB
844DEFUN ("process-kill-without-query", Fprocess_kill_without_query,
845 Sprocess_kill_without_query, 1, 2, 0,
846 "Say no query needed if PROCESS is running when Emacs is exited.\n\
f2d2dbfe 847Optional second argument if non-nil says to require a query.\n\
d0d6b7c5 848Value is t if a query was formerly required.")
4ee3e309
EN
849 (process, value)
850 register Lisp_Object process, value;
d0d6b7c5
JB
851{
852 Lisp_Object tem;
853
4ee3e309
EN
854 CHECK_PROCESS (process, 0);
855 tem = XPROCESS (process)->kill_without_query;
856 XPROCESS (process)->kill_without_query = Fnull (value);
d0d6b7c5
JB
857
858 return Fnull (tem);
859}
312c9964 860
de282a05
RS
861DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
862 1, 1, 0,
863 "Return the contact info of PROCESS; t for a real child.\n\
864For a net connection, the value is a cons cell of the form (HOST SERVICE).")
865 (process)
866 register Lisp_Object process;
867{
868 CHECK_PROCESS (process, 0);
869 return XPROCESS (process)->childp;
870}
871
312c9964
RS
872#if 0 /* Turned off because we don't currently record this info
873 in the process. Perhaps add it. */
874DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
875 "Return the connection type of `PROCESS'.\n\
876The value is `nil' for a pipe,\n\
877`t' or `pty' for a pty, or `stream' for a socket connection.")
878 (process)
879 Lisp_Object process;
880{
881 return XPROCESS (process)->type;
882}
883#endif
d0d6b7c5
JB
884\f
885Lisp_Object
886list_processes_1 ()
887{
888 register Lisp_Object tail, tem;
889 Lisp_Object proc, minspace, tem1;
890 register struct buffer *old = current_buffer;
891 register struct Lisp_Process *p;
892 register int state;
893 char tembuf[80];
894
22719df2 895 XSETFASTINT (minspace, 1);
d0d6b7c5
JB
896
897 set_buffer_internal (XBUFFER (Vstandard_output));
898 Fbuffer_disable_undo (Vstandard_output);
899
900 current_buffer->truncate_lines = Qt;
901
902 write_string ("\
a9fde32e
KH
903Proc Status Buffer Tty Command\n\
904---- ------ ------ --- -------\n", -1);
d0d6b7c5
JB
905
906 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
907 {
908 Lisp_Object symbol;
909
910 proc = Fcdr (Fcar (tail));
911 p = XPROCESS (proc);
912 if (NILP (p->childp))
913 continue;
914
915 Finsert (1, &p->name);
916 Findent_to (make_number (13), minspace);
917
918 if (!NILP (p->raw_status_low))
919 update_status (p);
920 symbol = p->status;
bcd69aea 921 if (CONSP (p->status))
d0d6b7c5
JB
922 symbol = XCONS (p->status)->car;
923
924
925 if (EQ (symbol, Qsignal))
926 {
927 Lisp_Object tem;
928 tem = Fcar (Fcdr (p->status));
929#ifdef VMS
930 if (XINT (tem) < NSIG)
b0310da4 931 write_string (sys_errlist [XINT (tem)], -1);
d0d6b7c5
JB
932 else
933#endif
934 Fprinc (symbol, Qnil);
935 }
936 else if (NETCONN_P (proc))
937 {
938 if (EQ (symbol, Qrun))
939 write_string ("open", -1);
940 else if (EQ (symbol, Qexit))
941 write_string ("closed", -1);
942 else
943 Fprinc (symbol, Qnil);
944 }
945 else
946 Fprinc (symbol, Qnil);
947
948 if (EQ (symbol, Qexit))
949 {
950 Lisp_Object tem;
951 tem = Fcar (Fcdr (p->status));
952 if (XFASTINT (tem))
953 {
3162bafa 954 sprintf (tembuf, " %d", (int) XFASTINT (tem));
d0d6b7c5
JB
955 write_string (tembuf, -1);
956 }
957 }
958
959 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
960 remove_process (proc);
961
962 Findent_to (make_number (22), minspace);
963 if (NILP (p->buffer))
964 insert_string ("(none)");
965 else if (NILP (XBUFFER (p->buffer)->name))
966 insert_string ("(Killed)");
967 else
968 Finsert (1, &XBUFFER (p->buffer)->name);
969
970 Findent_to (make_number (37), minspace);
971
a9fde32e
KH
972 if (STRINGP (p->tty_name))
973 Finsert (1, &p->tty_name);
974 else
975 insert_string ("(none)");
976
977 Findent_to (make_number (49), minspace);
978
d0d6b7c5
JB
979 if (NETCONN_P (proc))
980 {
981 sprintf (tembuf, "(network stream connection to %s)\n",
de282a05 982 XSTRING (XCONS (p->childp)->car)->data);
d0d6b7c5
JB
983 insert_string (tembuf);
984 }
985 else
986 {
987 tem = p->command;
988 while (1)
989 {
990 tem1 = Fcar (tem);
991 Finsert (1, &tem1);
992 tem = Fcdr (tem);
993 if (NILP (tem))
994 break;
995 insert_string (" ");
996 }
997 insert_string ("\n");
998 }
999 }
1000 return Qnil;
1001}
1002
1003DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 0, "",
1004 "Display a list of all processes.\n\
1005\(Any processes listed as Exited or Signaled are actually eliminated\n\
1006after the listing is made.)")
1007 ()
1008{
1009 internal_with_output_to_temp_buffer ("*Process List*",
1010 list_processes_1, Qnil);
1011 return Qnil;
1012}
1013
1014DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1015 "Return a list of all processes.")
1016 ()
1017{
1018 return Fmapcar (Qcdr, Vprocess_alist);
1019}
1020\f
b0310da4
JB
1021/* Starting asynchronous inferior processes. */
1022
1023static Lisp_Object start_process_unwind ();
1024
d0d6b7c5
JB
1025DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1026 "Start a program in a subprocess. Return the process object for it.\n\
1027Args are NAME BUFFER PROGRAM &rest PROGRAM-ARGS\n\
1028NAME is name for process. It is modified if necessary to make it unique.\n\
1029BUFFER is the buffer or (buffer-name) to associate with the process.\n\
1030 Process output goes at end of that buffer, unless you specify\n\
1031 an output stream or filter function to handle the output.\n\
1032 BUFFER may be also nil, meaning that this process is not associated\n\
0fa1789e 1033 with any buffer.\n\
d0d6b7c5
JB
1034Third arg is program file name. It is searched for as in the shell.\n\
1035Remaining arguments are strings to give program as arguments.")
1036 (nargs, args)
1037 int nargs;
1038 register Lisp_Object *args;
1039{
1e30af70 1040 Lisp_Object buffer, name, program, proc, current_dir, tem;
d0d6b7c5
JB
1041#ifdef VMS
1042 register unsigned char *new_argv;
1043 int len;
1044#else
1045 register unsigned char **new_argv;
1046#endif
1047 register int i;
b0310da4 1048 int count = specpdl_ptr - specpdl;
d0d6b7c5
JB
1049
1050 buffer = args[1];
1051 if (!NILP (buffer))
1052 buffer = Fget_buffer_create (buffer);
1053
1e30af70
JB
1054 /* Make sure that the child will be able to chdir to the current
1055 buffer's current directory, or its unhandled equivalent. We
1056 can't just have the child check for an error when it does the
1057 chdir, since it's in a vfork.
1058
1059 We have to GCPRO around this because Fexpand_file_name and
1060 Funhandled_file_name_directory might call a file name handling
1061 function. The argument list is protected by the caller, so all
1062 we really have to worry about is buffer. */
1063 {
1064 struct gcpro gcpro1, gcpro2;
1065
1066 current_dir = current_buffer->directory;
1067
1068 GCPRO2 (buffer, current_dir);
1069
7af71e17
RS
1070 current_dir
1071 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
1072 Qnil);
1e30af70
JB
1073 if (NILP (Ffile_accessible_directory_p (current_dir)))
1074 report_file_error ("Setting current directory",
1075 Fcons (current_buffer->directory, Qnil));
1076
1077 UNGCPRO;
1078 }
1079
d0d6b7c5
JB
1080 name = args[0];
1081 CHECK_STRING (name, 0);
1082
1083 program = args[2];
1084
1085 CHECK_STRING (program, 2);
1086
1087#ifdef VMS
1088 /* Make a one member argv with all args concatenated
1089 together separated by a blank. */
1090 len = XSTRING (program)->size + 2;
1091 for (i = 3; i < nargs; i++)
1092 {
1093 tem = args[i];
1094 CHECK_STRING (tem, i);
1095 len += XSTRING (tem)->size + 1; /* count the blank */
1096 }
1097 new_argv = (unsigned char *) alloca (len);
1098 strcpy (new_argv, XSTRING (program)->data);
1099 for (i = 3; i < nargs; i++)
1100 {
1101 tem = args[i];
1102 CHECK_STRING (tem, i);
1103 strcat (new_argv, " ");
1104 strcat (new_argv, XSTRING (tem)->data);
1105 }
b0310da4
JB
1106 /* Need to add code here to check for program existence on VMS */
1107
d0d6b7c5
JB
1108#else /* not VMS */
1109 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1110
d0d6b7c5 1111 /* If program file name is not absolute, search our path for it */
e98d950b
RS
1112 if (!IS_DIRECTORY_SEP (XSTRING (program)->data[0])
1113 && !(XSTRING (program)->size > 1
1114 && IS_DEVICE_SEP (XSTRING (program)->data[1])))
d0d6b7c5 1115 {
3b639868
KH
1116 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1117
d0d6b7c5 1118 tem = Qnil;
3b639868 1119 GCPRO4 (name, program, buffer, current_dir);
5437e9f9 1120 openp (Vexec_path, program, EXEC_SUFFIXES, &tem, 1);
3b639868 1121 UNGCPRO;
d0d6b7c5
JB
1122 if (NILP (tem))
1123 report_file_error ("Searching for program", Fcons (program, Qnil));
f8a87498 1124 tem = Fexpand_file_name (tem, Qnil);
d0d6b7c5
JB
1125 new_argv[0] = XSTRING (tem)->data;
1126 }
3b639868 1127 else
13373f4e
RS
1128 {
1129 if (!NILP (Ffile_directory_p (program)))
1130 error ("Specified program for new process is a directory");
1131
1132 new_argv[0] = XSTRING (program)->data;
1133 }
3b639868
KH
1134
1135 for (i = 3; i < nargs; i++)
1136 {
1137 tem = args[i];
1138 CHECK_STRING (tem, i);
1139 new_argv[i - 2] = XSTRING (tem)->data;
1140 }
1141 new_argv[i - 2] = 0;
d0d6b7c5
JB
1142#endif /* not VMS */
1143
1144 proc = make_process (name);
b0310da4
JB
1145 /* If an error occurs and we can't start the process, we want to
1146 remove it from the process list. This means that each error
1147 check in create_process doesn't need to call remove_process
1148 itself; it's all taken care of here. */
1149 record_unwind_protect (start_process_unwind, proc);
d0d6b7c5
JB
1150
1151 XPROCESS (proc)->childp = Qt;
1152 XPROCESS (proc)->command_channel_p = Qnil;
1153 XPROCESS (proc)->buffer = buffer;
1154 XPROCESS (proc)->sentinel = Qnil;
1155 XPROCESS (proc)->filter = Qnil;
1156 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1157
7af71e17
RS
1158 /* Make the process marker point into the process buffer (if any). */
1159 if (!NILP (buffer))
1160 Fset_marker (XPROCESS (proc)->mark,
1161 make_number (BUF_ZV (XBUFFER (buffer))), buffer);
1162
c7580538
KH
1163 if (!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters)
1164 || NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters))
1165 {
1166 XPROCESS (proc)->decode_coding_system = Qnil;
1167 XPROCESS (proc)->encode_coding_system = Qnil;
1168 }
1169 else
1170 {
1171 /* Setup coding systems for communicating with the process. */
1172 /* Qt denotes that we have not yet called Ffind_coding_system. */
1173 Lisp_Object coding_systems = Qt;
1174 Lisp_Object val, *args2;
1175 struct gcpro gcpro1;
0fa1789e 1176
c7580538
KH
1177 if (NILP (val = Vcoding_system_for_read))
1178 {
1179 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1180 args2[0] = Qstart_process;
1181 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1182 GCPRO1 (proc);
1183 coding_systems = Ffind_coding_system (nargs + 1, args2);
1184 UNGCPRO;
1185 if (CONSP (coding_systems))
1186 val = XCONS (coding_systems)->car;
83502605
KH
1187 else if (CONSP (Vdefault_process_coding_system))
1188 val = XCONS (Vdefault_process_coding_system)->car;
c7580538
KH
1189 }
1190 XPROCESS (proc)->decode_coding_system = val;
0fa1789e 1191
c7580538
KH
1192 if (NILP (val = Vcoding_system_for_write))
1193 {
1194 if (EQ (coding_systems, Qt))
1195 {
1196 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1197 args2[0] = Qstart_process;
1198 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1199 GCPRO1 (proc);
1200 coding_systems = Ffind_coding_system (nargs + 1, args2);
1201 UNGCPRO;
1202 }
1203 if (CONSP (coding_systems))
1204 val = XCONS (coding_systems)->cdr;
83502605
KH
1205 else if (CONSP (Vdefault_process_coding_system))
1206 val = XCONS (Vdefault_process_coding_system)->cdr;
c7580538
KH
1207 }
1208 XPROCESS (proc)->encode_coding_system = val;
1209 }
0fa1789e
KH
1210
1211 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1212 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1213
1e30af70 1214 create_process (proc, new_argv, current_dir);
d0d6b7c5 1215
b0310da4 1216 return unbind_to (count, proc);
d0d6b7c5
JB
1217}
1218
b0310da4 1219/* This function is the unwind_protect form for Fstart_process. If
8e6208c5 1220 PROC doesn't have its pid set, then we know someone has signaled
b0310da4
JB
1221 an error and the process wasn't started successfully, so we should
1222 remove it from the process list. */
1223static Lisp_Object
1224start_process_unwind (proc)
1225 Lisp_Object proc;
1226{
bcd69aea 1227 if (!PROCESSP (proc))
b0310da4
JB
1228 abort ();
1229
1230 /* Was PROC started successfully? */
188d6c4e 1231 if (XINT (XPROCESS (proc)->pid) <= 0)
b0310da4
JB
1232 remove_process (proc);
1233
1234 return Qnil;
1235}
1236
1237
d0d6b7c5
JB
1238SIGTYPE
1239create_process_1 (signo)
1240 int signo;
1241{
3c0ee47b 1242#if defined (USG) && !defined (POSIX_SIGNALS)
d0d6b7c5
JB
1243 /* USG systems forget handlers when they are used;
1244 must reestablish each time */
1245 signal (signo, create_process_1);
1246#endif /* USG */
1247}
1248
1249#if 0 /* This doesn't work; see the note before sigchld_handler. */
1250#ifdef USG
1251#ifdef SIGCHLD
1252/* Mimic blocking of signals on system V, which doesn't really have it. */
1253
1254/* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1255int sigchld_deferred;
1256
1257SIGTYPE
1258create_process_sigchld ()
1259{
1260 signal (SIGCHLD, create_process_sigchld);
1261
1262 sigchld_deferred = 1;
1263}
1264#endif
1265#endif
1266#endif
1267
1268#ifndef VMS /* VMS version of this function is in vmsproc.c. */
1e30af70 1269create_process (process, new_argv, current_dir)
d0d6b7c5
JB
1270 Lisp_Object process;
1271 char **new_argv;
1e30af70 1272 Lisp_Object current_dir;
d0d6b7c5 1273{
ecd1f654 1274 int pid, inchannel, outchannel;
d0d6b7c5 1275 int sv[2];
0dc70c33
KH
1276#ifdef POSIX_SIGNALS
1277 sigset_t procmask;
1278 sigset_t blocked;
1279 struct sigaction sigint_action;
1280 struct sigaction sigquit_action;
1281#ifdef AIX
1282 struct sigaction sighup_action;
1283#endif
1284#else /* !POSIX_SIGNALS */
d0d6b7c5
JB
1285#ifdef SIGCHLD
1286 SIGTYPE (*sigchld)();
1287#endif
0dc70c33 1288#endif /* !POSIX_SIGNALS */
ecd1f654
KH
1289 /* Use volatile to protect variables from being clobbered by longjmp. */
1290 volatile int forkin, forkout;
1291 volatile int pty_flag = 0;
d0d6b7c5
JB
1292 extern char **environ;
1293
d0d6b7c5
JB
1294 inchannel = outchannel = -1;
1295
1296#ifdef HAVE_PTYS
fe45da4e 1297 if (!NILP (Vprocess_connection_type))
d0d6b7c5
JB
1298 outchannel = inchannel = allocate_pty ();
1299
d0d6b7c5
JB
1300 if (inchannel >= 0)
1301 {
1302#ifndef USG
1303 /* On USG systems it does not work to open the pty's tty here
1304 and then close and reopen it in the child. */
1305#ifdef O_NOCTTY
1306 /* Don't let this terminal become our controlling terminal
1307 (in case we don't have one). */
1308 forkout = forkin = open (pty_name, O_RDWR | O_NOCTTY, 0);
1309#else
1310 forkout = forkin = open (pty_name, O_RDWR, 0);
1311#endif
1312 if (forkin < 0)
1313 report_file_error ("Opening pty", Qnil);
1314#else
1315 forkin = forkout = -1;
1316#endif /* not USG */
1317 pty_flag = 1;
1318 }
1319 else
1320#endif /* HAVE_PTYS */
1321#ifdef SKTPAIR
1322 {
1323 if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
1324 report_file_error ("Opening socketpair", Qnil);
1325 outchannel = inchannel = sv[0];
1326 forkout = forkin = sv[1];
1327 }
1328#else /* not SKTPAIR */
1329 {
1330 pipe (sv);
1331 inchannel = sv[0];
1332 forkout = sv[1];
1333 pipe (sv);
1334 outchannel = sv[1];
1335 forkin = sv[0];
1336 }
1337#endif /* not SKTPAIR */
1338
1339#if 0
1340 /* Replaced by close_process_descs */
1341 set_exclusive_use (inchannel);
1342 set_exclusive_use (outchannel);
1343#endif
1344
1345/* Stride people say it's a mystery why this is needed
1346 as well as the O_NDELAY, but that it fails without this. */
1347#if defined (STRIDE) || (defined (pfa) && defined (HAVE_PTYS))
1348 {
1349 int one = 1;
1350 ioctl (inchannel, FIONBIO, &one);
1351 }
1352#endif
1353
1354#ifdef O_NONBLOCK
1355 fcntl (inchannel, F_SETFL, O_NONBLOCK);
03832893 1356 fcntl (outchannel, F_SETFL, O_NONBLOCK);
d0d6b7c5
JB
1357#else
1358#ifdef O_NDELAY
1359 fcntl (inchannel, F_SETFL, O_NDELAY);
03832893 1360 fcntl (outchannel, F_SETFL, O_NDELAY);
d0d6b7c5
JB
1361#endif
1362#endif
1363
1364 /* Record this as an active process, with its channels.
1365 As a result, child_setup will close Emacs's side of the pipes. */
1366 chan_process[inchannel] = process;
1d056e64
KH
1367 XSETINT (XPROCESS (process)->infd, inchannel);
1368 XSETINT (XPROCESS (process)->outfd, outchannel);
d0d6b7c5
JB
1369 /* Record the tty descriptor used in the subprocess. */
1370 if (forkin < 0)
1371 XPROCESS (process)->subtty = Qnil;
1372 else
22719df2 1373 XSETFASTINT (XPROCESS (process)->subtty, forkin);
d0d6b7c5
JB
1374 XPROCESS (process)->pty_flag = (pty_flag ? Qt : Qnil);
1375 XPROCESS (process)->status = Qrun;
c7580538
KH
1376 if (!proc_decode_coding_system[inchannel])
1377 proc_decode_coding_system[inchannel]
1378 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
0fa1789e 1379 setup_coding_system (XPROCESS (process)->decode_coding_system,
c7580538
KH
1380 proc_decode_coding_system[inchannel]);
1381 if (!proc_encode_coding_system[outchannel])
1382 proc_encode_coding_system[outchannel]
1383 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
0fa1789e 1384 setup_coding_system (XPROCESS (process)->encode_coding_system,
c7580538 1385 proc_encode_coding_system[outchannel]);
d0d6b7c5
JB
1386
1387 /* Delay interrupts until we have a chance to store
1388 the new fork's pid in its process structure */
0dc70c33
KH
1389#ifdef POSIX_SIGNALS
1390 sigemptyset (&blocked);
1391#ifdef SIGCHLD
1392 sigaddset (&blocked, SIGCHLD);
1393#endif
1394#ifdef HAVE_VFORK
1395 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1396 this sets the parent's signal handlers as well as the child's.
1397 So delay all interrupts whose handlers the child might munge,
1398 and record the current handlers so they can be restored later. */
1399 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1400 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1401#ifdef AIX
1402 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1403#endif
1404#endif /* HAVE_VFORK */
1405 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1406#else /* !POSIX_SIGNALS */
d0d6b7c5
JB
1407#ifdef SIGCHLD
1408#ifdef BSD4_1
1409 sighold (SIGCHLD);
1410#else /* not BSD4_1 */
6df54671 1411#if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
d0d6b7c5
JB
1412 sigsetmask (sigmask (SIGCHLD));
1413#else /* ordinary USG */
1414#if 0
1415 sigchld_deferred = 0;
1416 sigchld = signal (SIGCHLD, create_process_sigchld);
1417#endif
1418#endif /* ordinary USG */
1419#endif /* not BSD4_1 */
1420#endif /* SIGCHLD */
0dc70c33 1421#endif /* !POSIX_SIGNALS */
d0d6b7c5 1422
3081bf8d 1423 FD_SET (inchannel, &input_wait_mask);
a69281ff 1424 FD_SET (inchannel, &non_keyboard_wait_mask);
3081bf8d
KH
1425 if (inchannel > max_process_desc)
1426 max_process_desc = inchannel;
1427
d0d6b7c5
JB
1428 /* Until we store the proper pid, enable sigchld_handler
1429 to recognize an unknown pid as standing for this process.
1430 It is very important not to let this `marker' value stay
1431 in the table after this function has returned; if it does
1432 it might cause call-process to hang and subsequent asynchronous
1433 processes to get their return values scrambled. */
1434 XSETINT (XPROCESS (process)->pid, -1);
1435
ececcbec
RS
1436 BLOCK_INPUT;
1437
d0d6b7c5
JB
1438 {
1439 /* child_setup must clobber environ on systems with true vfork.
1440 Protect it from permanent change. */
1441 char **save_environ = environ;
1442
e98d950b 1443#ifndef WINDOWSNT
d0d6b7c5
JB
1444 pid = vfork ();
1445 if (pid == 0)
e98d950b 1446#endif /* not WINDOWSNT */
d0d6b7c5
JB
1447 {
1448 int xforkin = forkin;
1449 int xforkout = forkout;
1450
1451#if 0 /* This was probably a mistake--it duplicates code later on,
1452 but fails to handle all the cases. */
1453 /* Make sure SIGCHLD is not blocked in the child. */
1454 sigsetmask (SIGEMPTYMASK);
1455#endif
1456
1457 /* Make the pty be the controlling terminal of the process. */
1458#ifdef HAVE_PTYS
1459 /* First, disconnect its current controlling terminal. */
1460#ifdef HAVE_SETSID
7ce48618
RS
1461 /* We tried doing setsid only if pty_flag, but it caused
1462 process_set_signal to fail on SGI when using a pipe. */
1463 setsid ();
ce4c9c90 1464 /* Make the pty's terminal the controlling terminal. */
084fd64a 1465 if (pty_flag)
39e9ebcd 1466 {
39e9ebcd
RS
1467#ifdef TIOCSCTTY
1468 /* We ignore the return value
1469 because faith@cs.unc.edu says that is necessary on Linux. */
1470 ioctl (xforkin, TIOCSCTTY, 0);
ce4c9c90 1471#endif
39e9ebcd 1472 }
d0d6b7c5 1473#else /* not HAVE_SETSID */
c14e53a4 1474#ifdef USG
000ab717 1475 /* It's very important to call setpgrp here and no time
d0d6b7c5
JB
1476 afterwards. Otherwise, we lose our controlling tty which
1477 is set when we open the pty. */
1478 setpgrp ();
1479#endif /* USG */
1480#endif /* not HAVE_SETSID */
9bcf8ec6
KH
1481#if defined (HAVE_TERMIOS) && defined (LDISC1)
1482 if (pty_flag && xforkin >= 0)
1483 {
1484 struct termios t;
1485 tcgetattr (xforkin, &t);
1486 t.c_lflag = LDISC1;
1487 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1488 write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1489 }
1490#else
aafadd9f 1491#if defined (NTTYDISC) && defined (TIOCSETD)
ff773a4e 1492 if (pty_flag && xforkin >= 0)
afc549fd
RS
1493 {
1494 /* Use new line discipline. */
1495 int ldisc = NTTYDISC;
4458f555 1496 ioctl (xforkin, TIOCSETD, &ldisc);
afc549fd 1497 }
000ab717 1498#endif
9bcf8ec6 1499#endif
d0d6b7c5
JB
1500#ifdef TIOCNOTTY
1501 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1502 can do TIOCSPGRP only to the process's controlling tty. */
1503 if (pty_flag)
1504 {
1505 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1506 I can't test it since I don't have 4.3. */
1507 int j = open ("/dev/tty", O_RDWR, 0);
1508 ioctl (j, TIOCNOTTY, 0);
1509 close (j);
5a570e37 1510#ifndef USG
d0d6b7c5
JB
1511 /* In order to get a controlling terminal on some versions
1512 of BSD, it is necessary to put the process in pgrp 0
1513 before it opens the terminal. */
99c1aeca 1514#ifdef HAVE_SETPGID
3ea1d291
RS
1515 setpgid (0, 0);
1516#else
d0d6b7c5 1517 setpgrp (0, 0);
3ea1d291 1518#endif
d0d6b7c5
JB
1519#endif
1520 }
1521#endif /* TIOCNOTTY */
1522
99153b9e 1523#if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
d0d6b7c5 1524/*** There is a suggestion that this ought to be a
99153b9e
RS
1525 conditional on TIOCSPGRP,
1526 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1527 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1528 that system does seem to need this code, even though
1529 both HAVE_SETSID and TIOCSCTTY are defined. */
d0d6b7c5
JB
1530 /* Now close the pty (if we had it open) and reopen it.
1531 This makes the pty the controlling terminal of the subprocess. */
1532 if (pty_flag)
1533 {
99e3d726
RS
1534#ifdef SET_CHILD_PTY_PGRP
1535 int pgrp = getpid ();
1536#endif
1537
d0d6b7c5
JB
1538 /* I wonder if close (open (pty_name, ...)) would work? */
1539 if (xforkin >= 0)
1540 close (xforkin);
1541 xforkout = xforkin = open (pty_name, O_RDWR, 0);
1542
4aa54ba8
RS
1543 if (xforkin < 0)
1544 {
1545 write (1, "Couldn't open the pty terminal ", 31);
1546 write (1, pty_name, strlen (pty_name));
1547 write (1, "\n", 1);
1548 _exit (1);
1549 }
1550
99e3d726
RS
1551#ifdef SET_CHILD_PTY_PGRP
1552 ioctl (xforkin, TIOCSPGRP, &pgrp);
1553 ioctl (xforkout, TIOCSPGRP, &pgrp);
1554#endif
d0d6b7c5 1555 }
99153b9e 1556#endif /* not UNIPLUS and not RTU and not DONT_REOPEN_PTY */
e9bf058b 1557
d0d6b7c5 1558#ifdef SETUP_SLAVE_PTY
13a72104
RS
1559 if (pty_flag)
1560 {
1561 SETUP_SLAVE_PTY;
1562 }
d0d6b7c5
JB
1563#endif /* SETUP_SLAVE_PTY */
1564#ifdef AIX
1565 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1566 Now reenable it in the child, so it will die when we want it to. */
1567 if (pty_flag)
1568 signal (SIGHUP, SIG_DFL);
1569#endif
1570#endif /* HAVE_PTYS */
1571
0dc70c33
KH
1572 signal (SIGINT, SIG_DFL);
1573 signal (SIGQUIT, SIG_DFL);
1574
1575 /* Stop blocking signals in the child. */
1576#ifdef POSIX_SIGNALS
1577 sigprocmask (SIG_SETMASK, &procmask, 0);
1578#else /* !POSIX_SIGNALS */
d0d6b7c5
JB
1579#ifdef SIGCHLD
1580#ifdef BSD4_1
1581 sigrelse (SIGCHLD);
1582#else /* not BSD4_1 */
6df54671 1583#if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
d0d6b7c5
JB
1584 sigsetmask (SIGEMPTYMASK);
1585#else /* ordinary USG */
63528b78 1586#if 0
d0d6b7c5 1587 signal (SIGCHLD, sigchld);
63528b78 1588#endif
d0d6b7c5
JB
1589#endif /* ordinary USG */
1590#endif /* not BSD4_1 */
1591#endif /* SIGCHLD */
0dc70c33 1592#endif /* !POSIX_SIGNALS */
5e7e1da2 1593
ab01d0a8
RS
1594 if (pty_flag)
1595 child_setup_tty (xforkout);
e98d950b
RS
1596#ifdef WINDOWSNT
1597 pid = child_setup (xforkin, xforkout, xforkout,
1598 new_argv, 1, current_dir);
1599#else /* not WINDOWSNT */
d0d6b7c5 1600 child_setup (xforkin, xforkout, xforkout,
e065a56e 1601 new_argv, 1, current_dir);
e98d950b 1602#endif /* not WINDOWSNT */
d0d6b7c5
JB
1603 }
1604 environ = save_environ;
1605 }
1606
ececcbec
RS
1607 UNBLOCK_INPUT;
1608
4a127b3b 1609 /* This runs in the Emacs process. */
d0d6b7c5 1610 if (pid < 0)
6311cf58
RS
1611 {
1612 if (forkin >= 0)
1613 close (forkin);
1614 if (forkin != forkout && forkout >= 0)
1615 close (forkout);
6311cf58 1616 }
4a127b3b
KH
1617 else
1618 {
1619 /* vfork succeeded. */
1620 XSETFASTINT (XPROCESS (process)->pid, pid);
d0d6b7c5 1621
e98d950b 1622#ifdef WINDOWSNT
4a127b3b 1623 register_child (pid, inchannel);
e98d950b
RS
1624#endif /* WINDOWSNT */
1625
4a127b3b
KH
1626 /* If the subfork execv fails, and it exits,
1627 this close hangs. I don't know why.
1628 So have an interrupt jar it loose. */
1629 stop_polling ();
1630 signal (SIGALRM, create_process_1);
1631 alarm (1);
1632 XPROCESS (process)->subtty = Qnil;
1633 if (forkin >= 0)
1634 close (forkin);
1635 alarm (0);
1636 start_polling ();
1637 if (forkin != forkout && forkout >= 0)
1638 close (forkout);
d0d6b7c5 1639
875e6b94 1640#ifdef HAVE_PTYS
4a127b3b
KH
1641 if (pty_flag)
1642 XPROCESS (process)->tty_name = build_string (pty_name);
1643 else
875e6b94 1644#endif
4a127b3b
KH
1645 XPROCESS (process)->tty_name = Qnil;
1646 }
3b9a3dfa 1647
4a127b3b
KH
1648 /* Restore the signal state whether vfork succeeded or not.
1649 (We will signal an error, below, if it failed.) */
0dc70c33
KH
1650#ifdef POSIX_SIGNALS
1651#ifdef HAVE_VFORK
1652 /* Restore the parent's signal handlers. */
1653 sigaction (SIGINT, &sigint_action, 0);
1654 sigaction (SIGQUIT, &sigquit_action, 0);
1655#ifdef AIX
1656 sigaction (SIGHUP, &sighup_action, 0);
1657#endif
1658#endif /* HAVE_VFORK */
1659 /* Stop blocking signals in the parent. */
1660 sigprocmask (SIG_SETMASK, &procmask, 0);
1661#else /* !POSIX_SIGNALS */
d0d6b7c5
JB
1662#ifdef SIGCHLD
1663#ifdef BSD4_1
1664 sigrelse (SIGCHLD);
1665#else /* not BSD4_1 */
6df54671 1666#if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
d0d6b7c5
JB
1667 sigsetmask (SIGEMPTYMASK);
1668#else /* ordinary USG */
1669#if 0
1670 signal (SIGCHLD, sigchld);
1671 /* Now really handle any of these signals
1672 that came in during this function. */
1673 if (sigchld_deferred)
1674 kill (getpid (), SIGCHLD);
1675#endif
1676#endif /* ordinary USG */
1677#endif /* not BSD4_1 */
1678#endif /* SIGCHLD */
0dc70c33 1679#endif /* !POSIX_SIGNALS */
4a127b3b
KH
1680
1681 /* Now generate the error if vfork failed. */
1682 if (pid < 0)
1683 report_file_error ("Doing vfork", Qnil);
d0d6b7c5
JB
1684}
1685#endif /* not VMS */
1686
1687#ifdef HAVE_SOCKETS
1688
1689/* open a TCP network connection to a given HOST/SERVICE. Treated
1690 exactly like a normal process when reading and writing. Only
1691 differences are in status display and process deletion. A network
1692 connection has no PID; you cannot signal it. All you can do is
1693 deactivate and close it via delete-process */
1694
1695DEFUN ("open-network-stream", Fopen_network_stream, Sopen_network_stream,
1696 4, 4, 0,
1697 "Open a TCP connection for a service to a host.\n\
1698Returns a subprocess-object to represent the connection.\n\
1699Input and output work as for subprocesses; `delete-process' closes it.\n\
1700Args are NAME BUFFER HOST SERVICE.\n\
1701NAME is name for process. It is modified if necessary to make it unique.\n\
1702BUFFER is the buffer (or buffer-name) to associate with the process.\n\
1703 Process output goes at end of that buffer, unless you specify\n\
1704 an output stream or filter function to handle the output.\n\
1705 BUFFER may be also nil, meaning that this process is not associated\n\
1706 with any buffer\n\
1707Third arg is name of the host to connect to, or its IP address.\n\
1708Fourth arg SERVICE is name of the service desired, or an integer\n\
1709 specifying a port number to connect to.")
1710 (name, buffer, host, service)
1711 Lisp_Object name, buffer, host, service;
1712{
1713 Lisp_Object proc;
1714 register int i;
1715 struct sockaddr_in address;
1716 struct servent *svc_info;
1717 struct hostent *host_info_ptr, host_info;
1718 char *(addr_list[2]);
79967d5e 1719 IN_ADDR numeric_addr;
d0d6b7c5
JB
1720 int s, outch, inch;
1721 char errstring[80];
1722 int port;
1723 struct hostent host_info_fixed;
1724 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
e333e864 1725 int retry = 0;
44ade2e9 1726 int count = specpdl_ptr - specpdl;
d0d6b7c5 1727
bff3ed0a
RS
1728#ifdef WINDOWSNT
1729 /* Ensure socket support is loaded if available. */
1730 init_winsock (TRUE);
1731#endif
1732
d0d6b7c5
JB
1733 GCPRO4 (name, buffer, host, service);
1734 CHECK_STRING (name, 0);
1735 CHECK_STRING (host, 0);
bcd69aea 1736 if (INTEGERP (service))
d0d6b7c5
JB
1737 port = htons ((unsigned short) XINT (service));
1738 else
1739 {
1740 CHECK_STRING (service, 0);
1741 svc_info = getservbyname (XSTRING (service)->data, "tcp");
1742 if (svc_info == 0)
1743 error ("Unknown service \"%s\"", XSTRING (service)->data);
1744 port = svc_info->s_port;
1745 }
1746
798b64bb
KH
1747 /* Slow down polling to every ten seconds.
1748 Some kernels have a bug which causes retrying connect to fail
1749 after a connect. Polling can interfere with gethostbyname too. */
1750#ifdef POLL_FOR_INPUT
1751 bind_polling_period (10);
1752#endif
1753
1d2c16fa 1754#ifndef TERM
616da37c
RS
1755 while (1)
1756 {
5f0929a7
RS
1757#ifdef TRY_AGAIN
1758 h_errno = 0;
1759#endif
5d6c2aa3
RS
1760 immediate_quit = 1;
1761 QUIT;
616da37c 1762 host_info_ptr = gethostbyname (XSTRING (host)->data);
5d6c2aa3 1763 immediate_quit = 0;
616da37c
RS
1764#ifdef TRY_AGAIN
1765 if (! (host_info_ptr == 0 && h_errno == TRY_AGAIN))
1766#endif
1767 break;
1768 Fsleep_for (make_number (1), Qnil);
1769 }
d0d6b7c5
JB
1770 if (host_info_ptr == 0)
1771 /* Attempt to interpret host as numeric inet address */
1772 {
393a9679 1773 numeric_addr = inet_addr ((char *) XSTRING (host)->data);
79967d5e 1774 if (NUMERIC_ADDR_ERROR)
d0d6b7c5
JB
1775 error ("Unknown host \"%s\"", XSTRING (host)->data);
1776
1777 host_info_ptr = &host_info;
1778 host_info.h_name = 0;
1779 host_info.h_aliases = 0;
1780 host_info.h_addrtype = AF_INET;
39a21be6
JB
1781#ifdef h_addr
1782 /* Older machines have only one address slot called h_addr.
1783 Newer machines have h_addr_list, but #define h_addr to
1784 be its first element. */
1785 host_info.h_addr_list = &(addr_list[0]);
1786#endif
1787 host_info.h_addr = (char*)(&numeric_addr);
d0d6b7c5 1788 addr_list[1] = 0;
8777fbe2
RS
1789 /* numeric_addr isn't null-terminated; it has fixed length. */
1790 host_info.h_length = sizeof (numeric_addr);
d0d6b7c5
JB
1791 }
1792
1793 bzero (&address, sizeof address);
1794 bcopy (host_info_ptr->h_addr, (char *) &address.sin_addr,
1795 host_info_ptr->h_length);
1796 address.sin_family = host_info_ptr->h_addrtype;
1797 address.sin_port = port;
1798
1799 s = socket (host_info_ptr->h_addrtype, SOCK_STREAM, 0);
1800 if (s < 0)
1801 report_file_error ("error creating socket", Fcons (name, Qnil));
1802
457a9bee
RS
1803 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1804 when connect is interrupted. So let's not let it get interrupted.
1805 Note we do not turn off polling, because polling is only used
1806 when not interrupt_input, and thus not normally used on the systems
1807 which have this bug. On systems which use polling, there's no way
1808 to quit if polling is turned off. */
1809 if (interrupt_input)
1810 unrequest_sigio ();
1811
d0d6b7c5 1812 loop:
0f2ee0c1
RS
1813
1814 immediate_quit = 1;
1815 QUIT;
1816
e333e864
RS
1817 if (connect (s, (struct sockaddr *) &address, sizeof address) == -1
1818 && errno != EISCONN)
d0d6b7c5
JB
1819 {
1820 int xerrno = errno;
e333e864 1821
0f2ee0c1
RS
1822 immediate_quit = 0;
1823
d0d6b7c5
JB
1824 if (errno == EINTR)
1825 goto loop;
e333e864
RS
1826 if (errno == EADDRINUSE && retry < 20)
1827 {
4590788a
RS
1828 /* A delay here is needed on some FreeBSD systems,
1829 and it is harmless, since this retrying takes time anyway
1830 and should be infrequent. */
1831 Fsleep_for (make_number (1), Qnil);
e333e864
RS
1832 retry++;
1833 goto loop;
1834 }
1835
d0d6b7c5 1836 close (s);
457a9bee
RS
1837
1838 if (interrupt_input)
1839 request_sigio ();
1840
d0d6b7c5
JB
1841 errno = xerrno;
1842 report_file_error ("connection failed",
1843 Fcons (host, Fcons (name, Qnil)));
1844 }
457a9bee 1845
0f2ee0c1
RS
1846 immediate_quit = 0;
1847
44ade2e9
RS
1848#ifdef POLL_FOR_INPUT
1849 unbind_to (count, Qnil);
1850#endif
1851
457a9bee
RS
1852 if (interrupt_input)
1853 request_sigio ();
1854
1d2c16fa
RS
1855#else /* TERM */
1856 s = connect_server (0);
1857 if (s < 0)
1858 report_file_error ("error creating socket", Fcons (name, Qnil));
1859 send_command (s, C_PORT, 0, "%s:%d", XSTRING (host)->data, ntohs (port));
1860 send_command (s, C_DUMB, 1, 0);
1861#endif /* TERM */
d0d6b7c5
JB
1862
1863 inch = s;
59f23005 1864 outch = s;
d0d6b7c5
JB
1865
1866 if (!NILP (buffer))
1867 buffer = Fget_buffer_create (buffer);
1868 proc = make_process (name);
1869
1870 chan_process[inch] = proc;
1871
1872#ifdef O_NONBLOCK
1873 fcntl (inch, F_SETFL, O_NONBLOCK);
1874#else
1875#ifdef O_NDELAY
1876 fcntl (inch, F_SETFL, O_NDELAY);
1877#endif
1878#endif
1879
de282a05 1880 XPROCESS (proc)->childp = Fcons (host, Fcons (service, Qnil));
d0d6b7c5
JB
1881 XPROCESS (proc)->command_channel_p = Qnil;
1882 XPROCESS (proc)->buffer = buffer;
1883 XPROCESS (proc)->sentinel = Qnil;
1884 XPROCESS (proc)->filter = Qnil;
1885 XPROCESS (proc)->command = Qnil;
1886 XPROCESS (proc)->pid = Qnil;
7795ff9b 1887 XSETINT (XPROCESS (proc)->infd, inch);
1d056e64 1888 XSETINT (XPROCESS (proc)->outfd, outch);
d0d6b7c5
JB
1889 XPROCESS (proc)->status = Qrun;
1890 FD_SET (inch, &input_wait_mask);
a69281ff 1891 FD_SET (inch, &non_keyboard_wait_mask);
7d0e672e
RS
1892 if (inch > max_process_desc)
1893 max_process_desc = inch;
d0d6b7c5 1894
c7580538
KH
1895 if (!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters)
1896 || NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters))
1897 {
1898 XPROCESS (proc)->decode_coding_system = Qnil;
1899 XPROCESS (proc)->encode_coding_system = Qnil;
1900 }
1901 else
1902 {
1903 /* Setup coding systems for communicating with the network stream. */
1904 struct gcpro gcpro1;
1905 /* Qt denotes that we have not yet called Ffind_coding_system. */
1906 Lisp_Object coding_systems = Qt;
1907 Lisp_Object args[5], val;
0fa1789e 1908
c7580538
KH
1909 if (NILP (val = Vcoding_system_for_read))
1910 {
1911 args[0] = Qopen_network_stream, args[1] = name,
1912 args[2] = buffer, args[3] = host, args[4] = service;
1913 GCPRO1 (proc);
1914 coding_systems = Ffind_coding_system (5, args);
1915 UNGCPRO;
83502605
KH
1916 if (CONSP (coding_systems))
1917 val = XCONS (coding_systems)->car;
1918 else if (CONSP (Vdefault_process_coding_system))
1919 val = XCONS (Vdefault_process_coding_system)->car;
c7580538
KH
1920 }
1921 XPROCESS (proc)->decode_coding_system = val;
0fa1789e 1922
c7580538
KH
1923 if (NILP (val = Vcoding_system_for_write))
1924 {
1925 if (EQ (coding_systems, Qt))
1926 {
1927 args[0] = Qopen_network_stream, args[1] = name,
1928 args[2] = buffer, args[3] = host, args[4] = service;
1929 GCPRO1 (proc);
1930 coding_systems = Ffind_coding_system (5, args);
1931 UNGCPRO;
1932 }
83502605
KH
1933 if (CONSP (coding_systems))
1934 val = XCONS (coding_systems)->cdr;
1935 else if (CONSP (Vdefault_process_coding_system))
1936 val = XCONS (Vdefault_process_coding_system)->cdr;
c7580538
KH
1937 }
1938 XPROCESS (proc)->encode_coding_system = val;
1939 }
0fa1789e 1940
c7580538
KH
1941 if (!proc_decode_coding_system[inch])
1942 proc_decode_coding_system[inch]
1943 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
0fa1789e 1944 setup_coding_system (XPROCESS (proc)->decode_coding_system,
c7580538
KH
1945 proc_decode_coding_system[inch]);
1946 if (!proc_encode_coding_system[outch])
1947 proc_encode_coding_system[outch]
1948 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
0fa1789e 1949 setup_coding_system (XPROCESS (proc)->encode_coding_system,
c7580538 1950 proc_encode_coding_system[outch]);
0fa1789e
KH
1951
1952 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1953 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1954
d0d6b7c5
JB
1955 UNGCPRO;
1956 return proc;
1957}
1958#endif /* HAVE_SOCKETS */
1959
1960deactivate_process (proc)
1961 Lisp_Object proc;
1962{
1963 register int inchannel, outchannel;
1964 register struct Lisp_Process *p = XPROCESS (proc);
1965
a9f2c884
RS
1966 inchannel = XINT (p->infd);
1967 outchannel = XINT (p->outfd);
d0d6b7c5 1968
a9f2c884 1969 if (inchannel >= 0)
d0d6b7c5
JB
1970 {
1971 /* Beware SIGCHLD hereabouts. */
1972 flush_pending_output (inchannel);
1973#ifdef VMS
1974 {
1975 VMS_PROC_STUFF *get_vms_process_pointer (), *vs;
1976 sys$dassgn (outchannel);
c6c6865d 1977 vs = get_vms_process_pointer (p->pid);
d0d6b7c5
JB
1978 if (vs)
1979 give_back_vms_process_stuff (vs);
1980 }
1981#else
1982 close (inchannel);
a9f2c884 1983 if (outchannel >= 0 && outchannel != inchannel)
d0d6b7c5
JB
1984 close (outchannel);
1985#endif
1986
1d056e64
KH
1987 XSETINT (p->infd, -1);
1988 XSETINT (p->outfd, -1);
d0d6b7c5
JB
1989 chan_process[inchannel] = Qnil;
1990 FD_CLR (inchannel, &input_wait_mask);
a69281ff 1991 FD_CLR (inchannel, &non_keyboard_wait_mask);
7d0e672e
RS
1992 if (inchannel == max_process_desc)
1993 {
1994 int i;
1995 /* We just closed the highest-numbered process input descriptor,
1996 so recompute the highest-numbered one now. */
1997 max_process_desc = 0;
1998 for (i = 0; i < MAXDESC; i++)
1999 if (!NILP (chan_process[i]))
2000 max_process_desc = i;
2001 }
d0d6b7c5
JB
2002 }
2003}
2004
2005/* Close all descriptors currently in use for communication
2006 with subprocess. This is used in a newly-forked subprocess
2007 to get rid of irrelevant descriptors. */
2008
2009close_process_descs ()
2010{
e98d950b 2011#ifndef WINDOWSNT
d0d6b7c5
JB
2012 int i;
2013 for (i = 0; i < MAXDESC; i++)
2014 {
2015 Lisp_Object process;
2016 process = chan_process[i];
2017 if (!NILP (process))
2018 {
a9f2c884
RS
2019 int in = XINT (XPROCESS (process)->infd);
2020 int out = XINT (XPROCESS (process)->outfd);
2021 if (in >= 0)
d0d6b7c5 2022 close (in);
a9f2c884 2023 if (out >= 0 && in != out)
d0d6b7c5
JB
2024 close (out);
2025 }
2026 }
e98d950b 2027#endif
d0d6b7c5
JB
2028}
2029\f
2030DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
2031 0, 3, 0,
2032 "Allow any pending output from subprocesses to be read by Emacs.\n\
2033It is read into the process' buffers or given to their filter functions.\n\
2034Non-nil arg PROCESS means do not return until some output has been received\n\
2035from PROCESS.\n\
2036Non-nil second arg TIMEOUT and third arg TIMEOUT-MSECS are number of\n\
2037seconds and microseconds to wait; return after that much time whether\n\
2038or not there is input.\n\
2039Return non-nil iff we received any output before the timeout expired.")
4ee3e309
EN
2040 (process, timeout, timeout_msecs)
2041 register Lisp_Object process, timeout, timeout_msecs;
d0d6b7c5
JB
2042{
2043 int seconds;
2044 int useconds;
2045
2046 if (! NILP (timeout_msecs))
2047 {
2048 CHECK_NUMBER (timeout_msecs, 2);
2049 useconds = XINT (timeout_msecs);
bcd69aea 2050 if (!INTEGERP (timeout))
1d056e64 2051 XSETINT (timeout, 0);
d0d6b7c5
JB
2052
2053 {
2054 int carry = useconds / 1000000;
2055
2056 XSETINT (timeout, XINT (timeout) + carry);
2057 useconds -= carry * 1000000;
2058
2059 /* I think this clause is necessary because C doesn't
2060 guarantee a particular rounding direction for negative
2061 integers. */
2062 if (useconds < 0)
2063 {
2064 XSETINT (timeout, XINT (timeout) - 1);
2065 useconds += 1000000;
2066 }
2067 }
2068 }
de946e5a
RS
2069 else
2070 useconds = 0;
d0d6b7c5
JB
2071
2072 if (! NILP (timeout))
2073 {
2074 CHECK_NUMBER (timeout, 1);
2075 seconds = XINT (timeout);
ada9a4fd 2076 if (seconds < 0 || (seconds == 0 && useconds == 0))
d0d6b7c5
JB
2077 seconds = -1;
2078 }
2079 else
2080 {
4ee3e309 2081 if (NILP (process))
d0d6b7c5
JB
2082 seconds = -1;
2083 else
2084 seconds = 0;
2085 }
2086
4ee3e309
EN
2087 if (NILP (process))
2088 XSETFASTINT (process, 0);
f76475ad 2089
d0d6b7c5 2090 return
4ee3e309 2091 (wait_reading_process_input (seconds, useconds, process, 0)
d0d6b7c5
JB
2092 ? Qt : Qnil);
2093}
2094
2095/* This variable is different from waiting_for_input in keyboard.c.
2096 It is used to communicate to a lisp process-filter/sentinel (via the
2097 function Fwaiting_for_user_input_p below) whether emacs was waiting
2098 for user-input when that process-filter was called.
2099 waiting_for_input cannot be used as that is by definition 0 when
d430ee71
RS
2100 lisp code is being evalled.
2101 This is also used in record_asynch_buffer_change.
2102 For that purpose, this must be 0
2103 when not inside wait_reading_process_input. */
d0d6b7c5
JB
2104static int waiting_for_user_input_p;
2105
c573ae8e
RS
2106/* This is here so breakpoints can be put on it. */
2107static
2108wait_reading_process_input_1 ()
2109{
2110}
2111
d0d6b7c5
JB
2112/* Read and dispose of subprocess output while waiting for timeout to
2113 elapse and/or keyboard input to be available.
2114
de6fd4b9 2115 TIME_LIMIT is:
d0d6b7c5
JB
2116 timeout in seconds, or
2117 zero for no limit, or
2118 -1 means gobble data immediately available but don't wait for any.
2119
de6fd4b9
RS
2120 MICROSECS is:
2121 an additional duration to wait, measured in microseconds.
2122 If this is nonzero and time_limit is 0, then the timeout
2123 consists of MICROSECS only.
6e4f3667 2124
de6fd4b9 2125 READ_KBD is a lisp value:
d0d6b7c5
JB
2126 0 to ignore keyboard input, or
2127 1 to return when input is available, or
84aa3ace 2128 -1 meaning caller will actually read the input, so don't throw to
d0d6b7c5 2129 the quit handler, or
e6194ffc 2130 a cons cell, meaning wait until its car is non-nil
de6fd4b9 2131 (and gobble terminal input into the buffer if any arrives), or
f76475ad
JB
2132 a process object, meaning wait until something arrives from that
2133 process. The return value is true iff we read some input from
2134 that process.
d0d6b7c5 2135
de6fd4b9 2136 DO_DISPLAY != 0 means redisplay should be done to show subprocess
d0d6b7c5
JB
2137 output that arrives.
2138
de6fd4b9 2139 If READ_KBD is a pointer to a struct Lisp_Process, then the
d0d6b7c5
JB
2140 function returns true iff we received input from that process
2141 before the timeout elapsed.
eb8c3be9 2142 Otherwise, return true iff we received input from any process. */
d0d6b7c5
JB
2143
2144wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
f76475ad
JB
2145 int time_limit, microsecs;
2146 Lisp_Object read_kbd;
2147 int do_display;
d0d6b7c5
JB
2148{
2149 register int channel, nfds, m;
2150 static SELECT_TYPE Available;
2151 int xerrno;
2152 Lisp_Object proc;
2153 EMACS_TIME timeout, end_time, garbage;
2154 SELECT_TYPE Atemp;
a9f2c884 2155 int wait_channel = -1;
d0d6b7c5
JB
2156 struct Lisp_Process *wait_proc = 0;
2157 int got_some_input = 0;
84aa3ace 2158 Lisp_Object *wait_for_cell = 0;
d0d6b7c5
JB
2159
2160 FD_ZERO (&Available);
2161
f76475ad
JB
2162 /* If read_kbd is a process to watch, set wait_proc and wait_channel
2163 accordingly. */
bcd69aea 2164 if (PROCESSP (read_kbd))
d0d6b7c5 2165 {
f76475ad 2166 wait_proc = XPROCESS (read_kbd);
a9f2c884 2167 wait_channel = XINT (wait_proc->infd);
22719df2 2168 XSETFASTINT (read_kbd, 0);
d0d6b7c5
JB
2169 }
2170
84aa3ace 2171 /* If waiting for non-nil in a cell, record where. */
bcd69aea 2172 if (CONSP (read_kbd))
84aa3ace
RS
2173 {
2174 wait_for_cell = &XCONS (read_kbd)->car;
22719df2 2175 XSETFASTINT (read_kbd, 0);
84aa3ace
RS
2176 }
2177
f76475ad 2178 waiting_for_user_input_p = XINT (read_kbd);
d0d6b7c5
JB
2179
2180 /* Since we may need to wait several times,
2181 compute the absolute time to return at. */
2182 if (time_limit || microsecs)
2183 {
2184 EMACS_GET_TIME (end_time);
2185 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
2186 EMACS_ADD_TIME (end_time, end_time, timeout);
2187 }
e07d5449
KH
2188#ifdef hpux
2189 /* AlainF 5-Jul-1996
2190 HP-UX 10.10 seem to have problems with signals coming in
2191 Causes "poll: interrupted system call" messages when Emacs is run
2192 in an X window
2193 Turn off periodic alarms (in case they are in use) */
2194 stop_polling ();
2195#endif
d0d6b7c5 2196
d0d6b7c5
JB
2197 while (1)
2198 {
c0239a0b
RS
2199 int timeout_reduced_for_timers = 0;
2200
d0d6b7c5
JB
2201 /* If calling from keyboard input, do not quit
2202 since we want to return C-g as an input character.
2203 Otherwise, do pending quit if requested. */
f76475ad 2204 if (XINT (read_kbd) >= 0)
d0d6b7c5
JB
2205 QUIT;
2206
889255b4
RS
2207 /* Exit now if the cell we're waiting for became non-nil. */
2208 if (wait_for_cell && ! NILP (*wait_for_cell))
2209 break;
2210
d0d6b7c5
JB
2211 /* Compute time from now till when time limit is up */
2212 /* Exit if already run out */
2213 if (time_limit == -1)
2214 {
2215 /* -1 specified for timeout means
2216 gobble output available now
2217 but don't wait at all. */
2218
2219 EMACS_SET_SECS_USECS (timeout, 0, 0);
2220 }
2221 else if (time_limit || microsecs)
2222 {
2223 EMACS_GET_TIME (timeout);
2224 EMACS_SUB_TIME (timeout, end_time, timeout);
2225 if (EMACS_TIME_NEG_P (timeout))
2226 break;
2227 }
2228 else
2229 {
2230 EMACS_SET_SECS_USECS (timeout, 100000, 0);
2231 }
2232
f854a00b
RS
2233 /* Normally we run timers here.
2234 But not if wait_for_cell; in those cases,
2235 the wait is supposed to be short,
2236 and those callers cannot handle running arbitrary Lisp code here. */
2237 if (! wait_for_cell)
fb4c3627 2238 {
c0239a0b 2239 EMACS_TIME timer_delay;
c573ae8e
RS
2240 int old_timers_run;
2241
2242 retry:
2243 old_timers_run = timers_run;
c0239a0b 2244 timer_delay = timer_check (1);
5de50bfb 2245 if (timers_run != old_timers_run && do_display)
c573ae8e
RS
2246 {
2247 redisplay_preserve_echo_area ();
2248 /* We must retry, since a timer may have requeued itself
2249 and that could alter the time_delay. */
2250 goto retry;
2251 }
2252
69645afc
RS
2253 /* If there is unread keyboard input, also return. */
2254 if (XINT (read_kbd) != 0
2255 && requeued_events_pending_p ())
2256 break;
2257
c0239a0b 2258 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
fb4c3627
RS
2259 {
2260 EMACS_TIME difference;
2261 EMACS_SUB_TIME (difference, timer_delay, timeout);
2262 if (EMACS_TIME_NEG_P (difference))
c0239a0b
RS
2263 {
2264 timeout = timer_delay;
2265 timeout_reduced_for_timers = 1;
2266 }
fb4c3627 2267 }
4abca5e7
RS
2268 /* If time_limit is -1, we are not going to wait at all. */
2269 else if (time_limit != -1)
c573ae8e
RS
2270 {
2271 /* This is so a breakpoint can be put here. */
2272 wait_reading_process_input_1 ();
2273 }
fb4c3627
RS
2274 }
2275
90ab1a81
JB
2276 /* Cause C-g and alarm signals to take immediate action,
2277 and cause input available signals to zero out timeout.
2278
2279 It is important that we do this before checking for process
2280 activity. If we get a SIGCHLD after the explicit checks for
2281 process activity, timeout is the only way we will know. */
2282 if (XINT (read_kbd) < 0)
2283 set_waiting_for_input (&timeout);
2284
6be429b1
JB
2285 /* If status of something has changed, and no input is
2286 available, notify the user of the change right away. After
2287 this explicit check, we'll let the SIGCHLD handler zap
2288 timeout to get our attention. */
2289 if (update_tick != process_tick && do_display)
2290 {
2291 Atemp = input_wait_mask;
2292 EMACS_SET_SECS_USECS (timeout, 0, 0);
0c9960e9
RS
2293 if ((select (max (max_process_desc, max_keyboard_desc) + 1,
2294 &Atemp, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
ecd1f654
KH
2295 &timeout)
2296 <= 0))
90ab1a81
JB
2297 {
2298 /* It's okay for us to do this and then continue with
a0e4d3f3 2299 the loop, since timeout has already been zeroed out. */
90ab1a81
JB
2300 clear_waiting_for_input ();
2301 status_notify ();
2302 }
6be429b1
JB
2303 }
2304
2305 /* Don't wait for output from a non-running process. */
2306 if (wait_proc != 0 && !NILP (wait_proc->raw_status_low))
2307 update_status (wait_proc);
2308 if (wait_proc != 0
2309 && ! EQ (wait_proc->status, Qrun))
9aa2a7f4 2310 {
7ce63188
RS
2311 int nread, total_nread;
2312
9aa2a7f4 2313 clear_waiting_for_input ();
7ce63188
RS
2314 XSETPROCESS (proc, wait_proc);
2315
2316 /* Read data from the process, until we exhaust it. */
1c0707fd 2317 while (XINT (wait_proc->infd) >= 0
97a084c1
RS
2318 && (nread
2319 = read_process_output (proc, XINT (wait_proc->infd))))
7ce63188
RS
2320 total_nread += nread;
2321 if (total_nread > 0 && do_display)
2322 redisplay_preserve_echo_area ();
2323
9aa2a7f4
JB
2324 break;
2325 }
6be429b1 2326
d0d6b7c5
JB
2327 /* Wait till there is something to do */
2328
b5dc1c83
RS
2329 if (wait_for_cell)
2330 Available = non_process_wait_mask;
2331 else if (! XINT (read_kbd))
a69281ff
RS
2332 Available = non_keyboard_wait_mask;
2333 else
2334 Available = input_wait_mask;
d0d6b7c5 2335
ff11dfa1 2336 /* If frame size has changed or the window is newly mapped,
ffd56f97
JB
2337 redisplay now, before we start to wait. There is a race
2338 condition here; if a SIGIO arrives between now and the select
016899c0
JB
2339 and indicates that a frame is trashed, the select may block
2340 displaying a trashed screen. */
5164ee8e 2341 if (frame_garbaged && do_display)
7286affd
RS
2342 {
2343 clear_waiting_for_input ();
2344 redisplay_preserve_echo_area ();
2345 if (XINT (read_kbd) < 0)
7efe788e 2346 set_waiting_for_input (&timeout);
7286affd 2347 }
ffd56f97 2348
0a65b032
RS
2349 if (XINT (read_kbd) && detect_input_pending ())
2350 {
2351 nfds = 0;
2352 FD_ZERO (&Available);
2353 }
2354 else
0c9960e9
RS
2355 nfds = select (max (max_process_desc, max_keyboard_desc) + 1,
2356 &Available, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
0a65b032 2357 &timeout);
6720a7fb 2358
d0d6b7c5
JB
2359 xerrno = errno;
2360
2361 /* Make C-g and alarm signals set flags again */
2362 clear_waiting_for_input ();
2363
2364 /* If we woke up due to SIGWINCH, actually change size now. */
2365 do_pending_window_change ();
2366
c0239a0b
RS
2367 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
2368 /* We wanted the full specified time, so return now. */
d0d6b7c5
JB
2369 break;
2370 if (nfds < 0)
2371 {
2372 if (xerrno == EINTR)
2373 FD_ZERO (&Available);
b0310da4
JB
2374#ifdef ultrix
2375 /* Ultrix select seems to return ENOMEM when it is
2376 interrupted. Treat it just like EINTR. Bleah. Note
2377 that we want to test for the "ultrix" CPP symbol, not
2378 "__ultrix__"; the latter is only defined under GCC, but
2379 not by DEC's bundled CC. -JimB */
8058415c
JB
2380 else if (xerrno == ENOMEM)
2381 FD_ZERO (&Available);
2382#endif
d0d6b7c5
JB
2383#ifdef ALLIANT
2384 /* This happens for no known reason on ALLIANT.
2385 I am guessing that this is the right response. -- RMS. */
2386 else if (xerrno == EFAULT)
2387 FD_ZERO (&Available);
2388#endif
2389 else if (xerrno == EBADF)
2390 {
2391#ifdef AIX
2392 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
2393 the child's closure of the pts gives the parent a SIGHUP, and
2394 the ptc file descriptor is automatically closed,
2395 yielding EBADF here or at select() call above.
2396 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
a0e4d3f3 2397 in m/ibmrt-aix.h), and here we just ignore the select error.
d0d6b7c5 2398 Cleanup occurs c/o status_notify after SIGCLD. */
ffd56f97 2399 FD_ZERO (&Available); /* Cannot depend on values returned */
d0d6b7c5
JB
2400#else
2401 abort ();
2402#endif
2403 }
2404 else
6ed6233b 2405 error ("select error: %s", strerror (xerrno));
d0d6b7c5 2406 }
26ec91de 2407#if defined(sun) && !defined(USG5_4)
a69281ff 2408 else if (nfds > 0 && keyboard_bit_set (&Available)
dd2281ae 2409 && interrupt_input)
e0109153
JB
2410 /* System sometimes fails to deliver SIGIO.
2411
2412 David J. Mackenzie says that Emacs doesn't compile under
2413 Solaris if this code is enabled, thus the USG5_4 in the CPP
2414 conditional. "I haven't noticed any ill effects so far.
2415 If you find a Solaris expert somewhere, they might know
2416 better." */
d0d6b7c5
JB
2417 kill (getpid (), SIGIO);
2418#endif
2419
5d5beb62
RS
2420#if 0 /* When polling is used, interrupt_input is 0,
2421 so get_input_pending should read the input.
2422 So this should not be needed. */
2423 /* If we are using polling for input,
2424 and we see input available, make it get read now.
2425 Otherwise it might not actually get read for a second.
2426 And on hpux, since we turn off polling in wait_reading_process_input,
2427 it might never get read at all if we don't spend much time
2428 outside of wait_reading_process_input. */
2429 if (XINT (read_kbd) && interrupt_input
2430 && keyboard_bit_set (&Available)
2431 && input_polling_used ())
2432 kill (getpid (), SIGALRM);
2433#endif
2434
d0d6b7c5
JB
2435 /* Check for keyboard input */
2436 /* If there is any, return immediately
2437 to give it higher priority than subprocesses */
2438
f854a00b 2439 if ((XINT (read_kbd) != 0)
5d6c2aa3 2440 && detect_input_pending_run_timers (do_display))
6ed6233b
KH
2441 {
2442 swallow_events (do_display);
5d6c2aa3 2443 if (detect_input_pending_run_timers (do_display))
6ed6233b
KH
2444 break;
2445 }
2446
69645afc
RS
2447 /* If there is unread keyboard input, also return. */
2448 if (XINT (read_kbd) != 0
2449 && requeued_events_pending_p ())
2450 break;
2451
f854a00b
RS
2452 /* If wait_for_cell. check for keyboard input
2453 but don't run any timers.
0c9960e9
RS
2454 The reason for this is so that X events will be processed.
2455 Otherwise they may have to wait until polling takes place.
2456 That would causes delays in pasting selections, for example. */
f854a00b
RS
2457 if (wait_for_cell
2458 && detect_input_pending ())
2459 {
2460 swallow_events (do_display);
0c9960e9 2461#if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
f854a00b
RS
2462 if (detect_input_pending ())
2463 break;
5d5beb62 2464#endif
0c9960e9 2465 }
f854a00b 2466
84aa3ace
RS
2467 /* Exit now if the cell we're waiting for became non-nil. */
2468 if (wait_for_cell && ! NILP (*wait_for_cell))
2469 break;
2470
4746118a 2471#ifdef SIGIO
5d5beb62 2472 /* If we think we have keyboard input waiting, but didn't get SIGIO,
d0d6b7c5
JB
2473 go read it. This can happen with X on BSD after logging out.
2474 In that case, there really is no input and no SIGIO,
2475 but select says there is input. */
2476
dd2281ae 2477 if (XINT (read_kbd) && interrupt_input
5d5beb62 2478 && keyboard_bit_set (&Available))
e643c5be 2479 kill (getpid (), SIGIO);
4746118a 2480#endif
d0d6b7c5 2481
d0d6b7c5
JB
2482 if (! wait_proc)
2483 got_some_input |= nfds > 0;
2484
32676c08
JB
2485 /* If checking input just got us a size-change event from X,
2486 obey it now if we should. */
97f3b3d6 2487 if (XINT (read_kbd) || wait_for_cell)
32676c08
JB
2488 do_pending_window_change ();
2489
a9f2c884
RS
2490 /* Check for data from a process. */
2491 /* Really FIRST_PROC_DESC should be 0 on Unix,
2492 but this is safer in the short run. */
a69281ff 2493 for (channel = 0; channel <= max_process_desc; channel++)
d0d6b7c5 2494 {
a69281ff
RS
2495 if (FD_ISSET (channel, &Available)
2496 && FD_ISSET (channel, &non_keyboard_wait_mask))
d0d6b7c5
JB
2497 {
2498 int nread;
2499
2500 /* If waiting for this channel, arrange to return as
2501 soon as no more input to be processed. No more
2502 waiting. */
2503 if (wait_channel == channel)
2504 {
a9f2c884 2505 wait_channel = -1;
d0d6b7c5
JB
2506 time_limit = -1;
2507 got_some_input = 1;
2508 }
2509 proc = chan_process[channel];
2510 if (NILP (proc))
2511 continue;
2512
d0d6b7c5
JB
2513 /* Read data from the process, starting with our
2514 buffered-ahead character if we have one. */
2515
2516 nread = read_process_output (proc, channel);
2517 if (nread > 0)
2518 {
2519 /* Since read_process_output can run a filter,
2520 which can call accept-process-output,
2521 don't try to read from any other processes
2522 before doing the select again. */
2523 FD_ZERO (&Available);
2524
2525 if (do_display)
2526 redisplay_preserve_echo_area ();
2527 }
2528#ifdef EWOULDBLOCK
2529 else if (nread == -1 && errno == EWOULDBLOCK)
2530 ;
0b75e9a4 2531#endif
89d7280d
RS
2532 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
2533 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
d0d6b7c5
JB
2534#ifdef O_NONBLOCK
2535 else if (nread == -1 && errno == EAGAIN)
2536 ;
2537#else
2538#ifdef O_NDELAY
2539 else if (nread == -1 && errno == EAGAIN)
2540 ;
2541 /* Note that we cannot distinguish between no input
2542 available now and a closed pipe.
2543 With luck, a closed pipe will be accompanied by
2544 subprocess termination and SIGCHLD. */
2545 else if (nread == 0 && !NETCONN_P (proc))
2546 ;
ffd56f97
JB
2547#endif /* O_NDELAY */
2548#endif /* O_NONBLOCK */
d0d6b7c5
JB
2549#ifdef HAVE_PTYS
2550 /* On some OSs with ptys, when the process on one end of
2551 a pty exits, the other end gets an error reading with
2552 errno = EIO instead of getting an EOF (0 bytes read).
2553 Therefore, if we get an error reading and errno =
2554 EIO, just continue, because the child process has
2555 exited and should clean itself up soon (e.g. when we
2556 get a SIGCHLD). */
2557 else if (nread == -1 && errno == EIO)
2558 ;
ffd56f97
JB
2559#endif /* HAVE_PTYS */
2560 /* If we can detect process termination, don't consider the process
2561 gone just because its pipe is closed. */
d0d6b7c5
JB
2562#ifdef SIGCHLD
2563 else if (nread == 0 && !NETCONN_P (proc))
2564 ;
2565#endif
2566 else
2567 {
2568 /* Preserve status of processes already terminated. */
2569 XSETINT (XPROCESS (proc)->tick, ++process_tick);
2570 deactivate_process (proc);
2571 if (!NILP (XPROCESS (proc)->raw_status_low))
2572 update_status (XPROCESS (proc));
2573 if (EQ (XPROCESS (proc)->status, Qrun))
2574 XPROCESS (proc)->status
2575 = Fcons (Qexit, Fcons (make_number (256), Qnil));
2576 }
2577 }
ffd56f97
JB
2578 } /* end for each file descriptor */
2579 } /* end while exit conditions not met */
d0d6b7c5 2580
d430ee71
RS
2581 waiting_for_user_input_p = 0;
2582
ffd56f97
JB
2583 /* If calling from keyboard input, do not quit
2584 since we want to return C-g as an input character.
2585 Otherwise, do pending quit if requested. */
f76475ad 2586 if (XINT (read_kbd) >= 0)
ffd56f97
JB
2587 {
2588 /* Prevent input_pending from remaining set if we quit. */
2589 clear_input_pending ();
2590 QUIT;
2591 }
e07d5449
KH
2592#ifdef hpux
2593 /* AlainF 5-Jul-1996
2594 HP-UX 10.10 seems to have problems with signals coming in
2595 Causes "poll: interrupted system call" messages when Emacs is run
2596 in an X window
2597 Turn periodic alarms back on */
5d5beb62 2598 start_polling ();
e07d5449
KH
2599#endif
2600
d0d6b7c5
JB
2601 return got_some_input;
2602}
2603\f
3b9a3dfa
RS
2604/* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
2605
2606static Lisp_Object
2607read_process_output_call (fun_and_args)
2608 Lisp_Object fun_and_args;
2609{
2610 return apply1 (XCONS (fun_and_args)->car, XCONS (fun_and_args)->cdr);
2611}
2612
2613static Lisp_Object
2614read_process_output_error_handler (error)
2615 Lisp_Object error;
2616{
2617 cmd_error_internal (error, "error in process filter: ");
2618 Vinhibit_quit = Qt;
2619 update_echo_area ();
833ba342 2620 Fsleep_for (make_number (2), Qnil);
3b9a3dfa
RS
2621}
2622
0fa1789e
KH
2623#ifdef WINDOWSNT
2624#define READ_CHILD_OUTPUT read_child_output
2625#else
2626#define READ_CHILD_OUTPUT read
2627#endif
2628
d0d6b7c5
JB
2629/* Read pending output from the process channel,
2630 starting with our buffered-ahead character if we have one.
0fa1789e 2631 Yield number of decoded characters read.
d0d6b7c5
JB
2632
2633 This function reads at most 1024 characters.
2634 If you want to read all available subprocess output,
0fa1789e
KH
2635 you must call it repeatedly until it returns zero.
2636
2637 The characters read are decoded according to PROC's coding-system
2638 for decoding. */
d0d6b7c5
JB
2639
2640read_process_output (proc, channel)
2641 Lisp_Object proc;
2642 register int channel;
2643{
2644 register int nchars;
d0d6b7c5 2645 char *chars;
0fa1789e
KH
2646#ifdef VMS
2647 int chars_allocated = 0; /* If 1, `chars' should be freed later. */
d0d6b7c5 2648#else
0fa1789e 2649 char buf[1024];
d0d6b7c5
JB
2650#endif
2651 register Lisp_Object outstream;
2652 register struct buffer *old = current_buffer;
2653 register struct Lisp_Process *p = XPROCESS (proc);
2654 register int opoint;
c7580538 2655 struct coding_system *coding = proc_decode_coding_system[channel];
0fa1789e
KH
2656 int chars_in_decoding_buf = 0; /* If 1, `chars' points
2657 XSTRING (p->decoding_buf)->data. */
d0d6b7c5
JB
2658
2659#ifdef VMS
2660 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
2661
2662 vs = get_vms_process_pointer (p->pid);
2663 if (vs)
2664 {
2665 if (!vs->iosb[0])
2666 return(0); /* Really weird if it does this */
2667 if (!(vs->iosb[0] & 1))
2668 return -1; /* I/O error */
2669 }
2670 else
2671 error ("Could not get VMS process pointer");
2672 chars = vs->inputBuffer;
2673 nchars = clean_vms_buffer (chars, vs->iosb[1]);
2674 if (nchars <= 0)
2675 {
2676 start_vms_process_read (vs); /* Crank up the next read on the process */
2677 return 1; /* Nothing worth printing, say we got 1 */
2678 }
0fa1789e
KH
2679 if (coding->carryover_size)
2680 {
2681 /* The data carried over in the previous decoding should be
2682 prepended to the new data read to decode all together. */
2683 char *buf = (char *) xmalloc (nchars + coding->carryover_size);
2684
2685 bcopy (coding->carryover, buf, coding->carryover_size);
2686 bcopy (chars, buf + coding->carryover_size, nchars);
2687 chars = buf;
2688 chars_allocated = 1;
2689 }
d0d6b7c5
JB
2690#else /* not VMS */
2691
0fa1789e
KH
2692 if (coding->carryover_size)
2693 /* The data carried over in the previous decoding should be
2694 prepended to the new data read to decode all together. */
2695 bcopy (coding->carryover, buf, coding->carryover_size);
2696
d0d6b7c5 2697 if (proc_buffered_char[channel] < 0)
0fa1789e
KH
2698 nchars = READ_CHILD_OUTPUT (channel, buf + coding->carryover_size,
2699 (sizeof buf) - coding->carryover_size);
d0d6b7c5
JB
2700 else
2701 {
0fa1789e 2702 buf[coding->carryover_size] = proc_buffered_char[channel];
d0d6b7c5 2703 proc_buffered_char[channel] = -1;
0fa1789e
KH
2704 nchars = READ_CHILD_OUTPUT (channel, buf + coding->carryover_size + 1,
2705 (sizeof buf) - coding->carryover_size - 1);
d0d6b7c5
JB
2706 if (nchars < 0)
2707 nchars = 1;
2708 else
2709 nchars = nchars + 1;
2710 }
0fa1789e 2711 chars = buf;
d0d6b7c5
JB
2712#endif /* not VMS */
2713
0fa1789e
KH
2714 /* At this point, NCHARS holds number of characters just received
2715 (including the one in proc_buffered_char[channel]). */
d0d6b7c5
JB
2716 if (nchars <= 0) return nchars;
2717
0fa1789e
KH
2718 /* Now set NCHARS how many bytes we must decode. */
2719 nchars += coding->carryover_size;
2720
2721 if (CODING_REQUIRE_CONVERSION (coding))
2722 {
2723 int require = decoding_buffer_size (coding, nchars);
2724 int consumed, produced;
2725
2726 if (XSTRING (p->decoding_buf)->size < require)
2727 p->decoding_buf = make_uninit_string (require);
2728 produced = decode_coding (coding, chars, XSTRING (p->decoding_buf)->data,
2729 nchars, XSTRING (p->decoding_buf)->size,
2730 &consumed);
2731
2732 /* New coding-system might be found by `decode_coding'. */
2733 if (!EQ (p->decode_coding_system, coding->symbol))
2734 {
2735 p->decode_coding_system = coding->symbol;
2736 setup_coding_system (coding->symbol,
c7580538 2737 proc_decode_coding_system[channel]);
0fa1789e
KH
2738 /* If coding-system for encoding is not yet decided, we set it
2739 as the same as coding-system for decoding. */
2740 if (NILP (p->encode_coding_system))
2741 {
2742 p->encode_coding_system = coding->symbol;
2743 setup_coding_system (coding->symbol,
c7580538 2744 proc_encode_coding_system[channel]);
0fa1789e
KH
2745 }
2746 }
2747#ifdef VMS
2748 /* Now we don't need the contents of `chars'. */
2749 if (chars_allocated)
2750 free (chars);
2751#endif
2752 if (produced == 0)
2753 return 0;
2754 chars = XSTRING (p->decoding_buf)->data;
2755 nchars = produced;
2756 chars_in_decoding_buf = 1;
2757 }
2758#ifdef VMS
2759 else if (chars_allocated)
2760 {
2761 /* Although we don't have to decode the received data, we must
2762 move it to an area which we don't have to free. */
2763 if (! STRINGP (p->decoding_buf)
2764 || XSTRING (p->decoding_buf)->size < nchars)
2765 p->decoding_buf = make_uninit_string (nchars);
2766 bcopy (chars, XSTRING (p->decoding_buf)->data, nchars);
2767 free (chars);
2768 chars = XSTRING (p->decoding_buf)->data;
2769 chars_in_decoding_buf = 1;
2770 }
2771#endif
2772
d0d6b7c5
JB
2773 outstream = p->filter;
2774 if (!NILP (outstream))
2775 {
2776 /* We inhibit quit here instead of just catching it so that
2777 hitting ^G when a filter happens to be running won't screw
2778 it up. */
2779 int count = specpdl_ptr - specpdl;
30c78175 2780 Lisp_Object odeactivate;
dfc21838 2781 Lisp_Object obuffer, okeymap;
4da2f5be 2782 int outer_running_asynch_code = running_asynch_code;
30c78175 2783
dfc21838
RS
2784 /* No need to gcpro these, because all we do with them later
2785 is test them for EQness, and none of them should be a string. */
30c78175 2786 odeactivate = Vdeactivate_mark;
dfc21838
RS
2787 XSETBUFFER (obuffer, current_buffer);
2788 okeymap = current_buffer->keymap;
30c78175 2789
d0d6b7c5 2790 specbind (Qinhibit_quit, Qt);
6545aada 2791 specbind (Qlast_nonmenu_event, Qt);
3b9a3dfa 2792
4da2f5be
RS
2793 /* In case we get recursively called,
2794 and we already saved the match data nonrecursively,
2795 save the same match data in safely recursive fashion. */
2796 if (outer_running_asynch_code)
2797 {
2798 Lisp_Object tem;
2799 /* Don't clobber the CURRENT match data, either! */
dd130227 2800 tem = Fmatch_data (Qnil, Qnil);
4da2f5be 2801 restore_match_data ();
dd130227 2802 record_unwind_protect (Fstore_match_data, Fmatch_data (Qnil, Qnil));
4da2f5be
RS
2803 Fstore_match_data (tem);
2804 }
2805
2806 /* For speed, if a search happens within this code,
2807 save the match data in a special nonrecursive fashion. */
7074fde6 2808 running_asynch_code = 1;
4da2f5be
RS
2809
2810 /* Read and dispose of the process output. */
3b9a3dfa
RS
2811 internal_condition_case_1 (read_process_output_call,
2812 Fcons (outstream,
2813 Fcons (proc,
7074fde6
FP
2814 Fcons (make_string (chars,
2815 nchars),
3b9a3dfa
RS
2816 Qnil))),
2817 !NILP (Vdebug_on_error) ? Qnil : Qerror,
2818 read_process_output_error_handler);
4da2f5be
RS
2819
2820 /* If we saved the match data nonrecursively, restore it now. */
7074fde6 2821 restore_match_data ();
4da2f5be 2822 running_asynch_code = outer_running_asynch_code;
d0d6b7c5 2823
592ce97f 2824 /* Handling the process output should not deactivate the mark. */
30c78175
RS
2825 Vdeactivate_mark = odeactivate;
2826
7973cfa8
RS
2827#if 0 /* Call record_asynch_buffer_change unconditionally,
2828 because we might have changed minor modes or other things
2829 that affect key bindings. */
dfc21838
RS
2830 if (! EQ (Fcurrent_buffer (), obuffer)
2831 || ! EQ (current_buffer->keymap, okeymap))
7973cfa8 2832#endif
927e08be
RS
2833 /* But do it only if the caller is actually going to read events.
2834 Otherwise there's no need to make him wake up, and it could
2835 cause trouble (for example it would make Fsit_for return). */
2836 if (waiting_for_user_input_p == -1)
2837 record_asynch_buffer_change ();
d72534ba 2838
d0d6b7c5
JB
2839#ifdef VMS
2840 start_vms_process_read (vs);
2841#endif
2ea6d561 2842 unbind_to (count, Qnil);
d0d6b7c5
JB
2843 return nchars;
2844 }
2845
2846 /* If no filter, write into buffer if it isn't dead. */
2847 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
2848 {
b0310da4 2849 Lisp_Object old_read_only;
12ca5cdf 2850 int old_begv, old_zv;
30c78175 2851 Lisp_Object odeactivate;
12ca5cdf 2852 int before;
30c78175
RS
2853
2854 odeactivate = Vdeactivate_mark;
d0d6b7c5
JB
2855
2856 Fset_buffer (p->buffer);
6ec8bbd2 2857 opoint = PT;
b0310da4 2858 old_read_only = current_buffer->read_only;
12ca5cdf
RS
2859 old_begv = BEGV;
2860 old_zv = ZV;
b0310da4
JB
2861
2862 current_buffer->read_only = Qnil;
d0d6b7c5
JB
2863
2864 /* Insert new output into buffer
2865 at the current end-of-output marker,
2866 thus preserving logical ordering of input and output. */
2867 if (XMARKER (p->mark)->buffer)
53aad33f 2868 SET_PT (clip_to_bounds (BEGV, marker_position (p->mark), ZV));
d0d6b7c5
JB
2869 else
2870 SET_PT (ZV);
12ca5cdf 2871 before = PT;
b0310da4
JB
2872
2873 /* If the output marker is outside of the visible region, save
2874 the restriction and widen. */
6ec8bbd2 2875 if (! (BEGV <= PT && PT <= ZV))
b0310da4
JB
2876 Fwiden ();
2877
d0d6b7c5
JB
2878 /* Insert before markers in case we are inserting where
2879 the buffer's mark is, and the user's next command is Meta-y. */
0fa1789e
KH
2880 if (chars_in_decoding_buf)
2881 insert_from_string_before_markers (p->decoding_buf, 0, nchars, 0);
2882 else
2883 insert_before_markers (chars, nchars);
6ec8bbd2 2884 Fset_marker (p->mark, make_number (PT), p->buffer);
b0310da4 2885
d0d6b7c5
JB
2886 update_mode_lines++;
2887
12ca5cdf
RS
2888 /* Make sure opoint and the old restrictions
2889 float ahead of any new text just as point would. */
2890 if (opoint >= before)
2891 opoint += PT - before;
2892 if (old_begv > before)
2893 old_begv += PT - before;
2894 if (old_zv >= before)
2895 old_zv += PT - before;
2896
b0310da4 2897 /* If the restriction isn't what it should be, set it. */
12ca5cdf
RS
2898 if (old_begv != BEGV || old_zv != ZV)
2899 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
b0310da4 2900
592ce97f 2901 /* Handling the process output should not deactivate the mark. */
30c78175
RS
2902 Vdeactivate_mark = odeactivate;
2903
b0310da4 2904 current_buffer->read_only = old_read_only;
d0d6b7c5
JB
2905 SET_PT (opoint);
2906 set_buffer_internal (old);
2907 }
2908#ifdef VMS
2909 start_vms_process_read (vs);
2910#endif
2911 return nchars;
2912}
2913
2914DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
2915 0, 0, 0,
8b4d685f 2916 "Returns non-nil if emacs is waiting for input from the user.\n\
d0d6b7c5
JB
2917This is intended for use by asynchronous process output filters and sentinels.")
2918 ()
2919{
8b4d685f 2920 return (waiting_for_user_input_p ? Qt : Qnil);
d0d6b7c5
JB
2921}
2922\f
2923/* Sending data to subprocess */
2924
2925jmp_buf send_process_frame;
2926
2927SIGTYPE
2928send_process_trap ()
2929{
2930#ifdef BSD4_1
2931 sigrelse (SIGPIPE);
2932 sigrelse (SIGALRM);
2933#endif /* BSD4_1 */
2934 longjmp (send_process_frame, 1);
2935}
2936
4556b700
RS
2937/* Send some data to process PROC.
2938 BUF is the beginning of the data; LEN is the number of characters.
0fa1789e
KH
2939 OBJECT is the Lisp object that the data comes from.
2940
2941 The data is encoded by PROC's coding-system for encoding before it
2942 is sent. But if the data ends at the middle of multi-byte
2943 representation, that incomplete sequence of bytes are sent without
2944 being encoded. Should we store them in a buffer to prepend them to
2945 the data send later? */
4556b700
RS
2946
2947send_process (proc, buf, len, object)
ecd1f654 2948 volatile Lisp_Object proc;
d0d6b7c5
JB
2949 char *buf;
2950 int len;
4556b700 2951 Lisp_Object object;
d0d6b7c5 2952{
ecd1f654 2953 /* Use volatile to protect variables from being clobbered by longjmp. */
d0d6b7c5 2954 int rv;
ecd1f654 2955 volatile unsigned char *procname = XSTRING (XPROCESS (proc)->name)->data;
0fa1789e 2956 struct coding_system *coding;
6044e593
RS
2957 struct gcpro gcpro1;
2958
2959 GCPRO1 (object);
d0d6b7c5 2960
d0d6b7c5
JB
2961#ifdef VMS
2962 struct Lisp_Process *p = XPROCESS (proc);
2963 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
2964#endif /* VMS */
2965
2966 if (! NILP (XPROCESS (proc)->raw_status_low))
2967 update_status (XPROCESS (proc));
2968 if (! EQ (XPROCESS (proc)->status, Qrun))
2969 error ("Process %s not running", procname);
0fa1789e
KH
2970 if (XINT (XPROCESS (proc)->outfd) < 0)
2971 error ("Output file descriptor of %s is closed", procname);
2972
c7580538 2973 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
0fa1789e
KH
2974 if (CODING_REQUIRE_CONVERSION (coding))
2975 {
2976 int require = encoding_buffer_size (coding, len);
2977 int offset, dummy;
2978 char *temp_buf = NULL;
2979
2980 /* Remember the offset of data because a string or a buffer may
2981 be relocated. Setting OFFSET to -1 means we don't have to
2982 care relocation. */
2983 offset = (BUFFERP (object)
2984 ? BUF_PTR_CHAR_POS (XBUFFER (object), (unsigned char *) buf)
2985 : (STRINGP (object)
2986 ? offset = buf - (char *) XSTRING (object)->data
2987 : -1));
2988
2989 if (coding->carryover_size > 0)
2990 {
2991 temp_buf = (char *) xmalloc (len + coding->carryover_size);
2992
2993 if (offset >= 0)
2994 {
2995 if (BUFFERP (object))
2996 buf = (char *) BUF_CHAR_ADDRESS (XBUFFER (object), offset);
2997 else if (STRINGP (object))
2998 buf = offset + (char *) XSTRING (object)->data;
2999 /* Now we don't have to care relocation. */
3000 offset = -1;
3001 }
3002 bcopy (coding->carryover, temp_buf, coding->carryover_size);
3003 bcopy (buf, temp_buf + coding->carryover_size, len);
3004 buf = temp_buf;
3005 }
3006
3007 if (XSTRING (XPROCESS (proc)->encoding_buf)->size < require)
3008 {
3009 XPROCESS (proc)->encoding_buf = make_uninit_string (require);
3010
3011 if (offset >= 0)
3012 {
3013 if (BUFFERP (object))
3014 buf = (char *) BUF_CHAR_ADDRESS (XBUFFER (object), offset);
3015 else if (STRINGP (object))
3016 buf = offset + (char *) XSTRING (object)->data;
3017 }
3018 }
3019 object = XPROCESS (proc)->encoding_buf;
3020 len = encode_coding (coding, buf, XSTRING (object)->data,
3021 len, XSTRING (object)->size, &dummy);
3022 buf = XSTRING (object)->data;
3023 if (temp_buf)
3024 xfree (temp_buf);
3025 }
d0d6b7c5
JB
3026
3027#ifdef VMS
3028 vs = get_vms_process_pointer (p->pid);
3029 if (vs == 0)
3030 error ("Could not find this process: %x", p->pid);
3031 else if (write_to_vms_process (vs, buf, len))
3032 ;
3033#else
4556b700
RS
3034
3035 if (pty_max_bytes == 0)
3036 {
3037#if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
3038 pty_max_bytes = fpathconf (XFASTINT (XPROCESS (proc)->outfd),
3039 _PC_MAX_CANON);
3040 if (pty_max_bytes < 0)
3041 pty_max_bytes = 250;
3042#else
3043 pty_max_bytes = 250;
3044#endif
3045 /* Deduct one, to leave space for the eof. */
3046 pty_max_bytes--;
3047 }
3048
d0d6b7c5
JB
3049 if (!setjmp (send_process_frame))
3050 while (len > 0)
3051 {
3052 int this = len;
4746118a 3053 SIGTYPE (*old_sigpipe)();
93b4f699
RS
3054 int flush_pty = 0;
3055
4556b700
RS
3056 /* Decide how much data we can send in one batch.
3057 Long lines need to be split into multiple batches. */
3058 if (!NILP (XPROCESS (proc)->pty_flag))
93b4f699 3059 {
4556b700
RS
3060 /* Starting this at zero is always correct when not the first iteration
3061 because the previous iteration ended by sending C-d.
3062 It may not be correct for the first iteration
3063 if a partial line was sent in a separate send_process call.
3064 If that proves worth handling, we need to save linepos
3065 in the process object. */
3066 int linepos = 0;
3067 char *ptr = buf;
3068 char *end = buf + len;
3069
3070 /* Scan through this text for a line that is too long. */
3071 while (ptr != end && linepos < pty_max_bytes)
3072 {
3073 if (*ptr == '\n')
3074 linepos = 0;
3075 else
3076 linepos++;
3077 ptr++;
3078 }
3079 /* If we found one, break the line there
3080 and put in a C-d to force the buffer through. */
3081 this = ptr - buf;
93b4f699
RS
3082 }
3083
4556b700
RS
3084 /* Send this batch, using one or more write calls. */
3085 while (this > 0)
d0d6b7c5 3086 {
4556b700
RS
3087 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
3088 rv = write (XINT (XPROCESS (proc)->outfd), buf, this);
3089 signal (SIGPIPE, old_sigpipe);
3090
3091 if (rv < 0)
3092 {
3093 if (0
d0d6b7c5 3094#ifdef EWOULDBLOCK
4556b700 3095 || errno == EWOULDBLOCK
d0d6b7c5
JB
3096#endif
3097#ifdef EAGAIN
4556b700 3098 || errno == EAGAIN
d0d6b7c5 3099#endif
4556b700
RS
3100 )
3101 /* Buffer is full. Wait, accepting input;
3102 that may allow the program
3103 to finish doing output and read more. */
3104 {
3105 Lisp_Object zero;
3106 int offset;
3107
3108 /* Running filters might relocate buffers or strings.
3109 Arrange to relocate BUF. */
3110 if (BUFFERP (object))
3111 offset = BUF_PTR_CHAR_POS (XBUFFER (object),
3112 (unsigned char *) buf);
3113 else if (STRINGP (object))
3114 offset = buf - (char *) XSTRING (object)->data;
3115
22719df2 3116 XSETFASTINT (zero, 0);
f3e6605c
RS
3117#ifdef EMACS_HAS_USECS
3118 wait_reading_process_input (0, 20000, zero, 0);
3119#else
4556b700 3120 wait_reading_process_input (1, 0, zero, 0);
f3e6605c 3121#endif
4556b700
RS
3122
3123 if (BUFFERP (object))
3124 buf = (char *) BUF_CHAR_ADDRESS (XBUFFER (object), offset);
3125 else if (STRINGP (object))
3126 buf = offset + (char *) XSTRING (object)->data;
3127
3128 rv = 0;
3129 }
3130 else
3131 /* This is a real error. */
3132 report_file_error ("writing to process", Fcons (proc, Qnil));
d0d6b7c5 3133 }
4556b700
RS
3134 buf += rv;
3135 len -= rv;
3136 this -= rv;
d0d6b7c5 3137 }
f76475ad 3138
4556b700
RS
3139 /* If we sent just part of the string, put in an EOF
3140 to force it through, before we send the rest. */
3141 if (len > 0)
3142 Fprocess_send_eof (proc);
d0d6b7c5
JB
3143 }
3144#endif
3145 else
3146 {
3147 XPROCESS (proc)->raw_status_low = Qnil;
3148 XPROCESS (proc)->raw_status_high = Qnil;
3149 XPROCESS (proc)->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
3150 XSETINT (XPROCESS (proc)->tick, ++process_tick);
3151 deactivate_process (proc);
3152#ifdef VMS
3153 error ("Error writing to process %s; closed it", procname);
3154#else
3155 error ("SIGPIPE raised on process %s; closed it", procname);
3156#endif
3157 }
6044e593
RS
3158
3159 UNGCPRO;
d0d6b7c5
JB
3160}
3161
3162DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
3163 3, 3, 0,
3164 "Send current contents of region as input to PROCESS.\n\
ebb9e16f
JB
3165PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
3166nil, indicating the current buffer's process.\n\
d0d6b7c5
JB
3167Called from program, takes three arguments, PROCESS, START and END.\n\
3168If the region is more than 500 characters long,\n\
3169it is sent in several bunches. This may happen even for shorter regions.\n\
3170Output from processes can arrive in between bunches.")
3171 (process, start, end)
3172 Lisp_Object process, start, end;
3173{
3174 Lisp_Object proc;
3175 int start1;
3176
3177 proc = get_process (process);
3178 validate_region (&start, &end);
3179
3180 if (XINT (start) < GPT && XINT (end) > GPT)
3181 move_gap (start);
3182
3183 start1 = XINT (start);
0fa1789e 3184 send_process (proc, POS_ADDR (start1), XINT (end) - XINT (start),
4556b700 3185 Fcurrent_buffer ());
d0d6b7c5
JB
3186
3187 return Qnil;
3188}
3189
3190DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
3191 2, 2, 0,
3192 "Send PROCESS the contents of STRING as input.\n\
ebb9e16f
JB
3193PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
3194nil, indicating the current buffer's process.\n\
d0d6b7c5
JB
3195If STRING is more than 500 characters long,\n\
3196it is sent in several bunches. This may happen even for shorter strings.\n\
3197Output from processes can arrive in between bunches.")
3198 (process, string)
3199 Lisp_Object process, string;
3200{
3201 Lisp_Object proc;
3202 CHECK_STRING (string, 1);
3203 proc = get_process (process);
4556b700 3204 send_process (proc, XSTRING (string)->data, XSTRING (string)->size, string);
d0d6b7c5
JB
3205 return Qnil;
3206}
3207\f
3208/* send a signal number SIGNO to PROCESS.
3209 CURRENT_GROUP means send to the process group that currently owns
3210 the terminal being used to communicate with PROCESS.
3211 This is used for various commands in shell mode.
3212 If NOMSG is zero, insert signal-announcements into process's buffers
b0310da4
JB
3213 right away.
3214
3215 If we can, we try to signal PROCESS by sending control characters
e333e864 3216 down the pty. This allows us to signal inferiors who have changed
b0310da4 3217 their uid, for which killpg would return an EPERM error. */
d0d6b7c5 3218
f9738840 3219static void
d0d6b7c5
JB
3220process_send_signal (process, signo, current_group, nomsg)
3221 Lisp_Object process;
3222 int signo;
3223 Lisp_Object current_group;
3224 int nomsg;
3225{
3226 Lisp_Object proc;
3227 register struct Lisp_Process *p;
3228 int gid;
3229 int no_pgrp = 0;
3230
3231 proc = get_process (process);
3232 p = XPROCESS (proc);
3233
3234 if (!EQ (p->childp, Qt))
3235 error ("Process %s is not a subprocess",
3236 XSTRING (p->name)->data);
a9f2c884 3237 if (XINT (p->infd) < 0)
d0d6b7c5
JB
3238 error ("Process %s is not active",
3239 XSTRING (p->name)->data);
3240
3241 if (NILP (p->pty_flag))
3242 current_group = Qnil;
3243
d0d6b7c5
JB
3244 /* If we are using pgrps, get a pgrp number and make it negative. */
3245 if (!NILP (current_group))
3246 {
b0310da4 3247#ifdef SIGNALS_VIA_CHARACTERS
d0d6b7c5
JB
3248 /* If possible, send signals to the entire pgrp
3249 by sending an input character to it. */
b0310da4 3250
6be429b1
JB
3251 /* TERMIOS is the latest and bestest, and seems most likely to
3252 work. If the system has it, use it. */
3253#ifdef HAVE_TERMIOS
3254 struct termios t;
3255
3256 switch (signo)
3257 {
3258 case SIGINT:
a9f2c884 3259 tcgetattr (XINT (p->infd), &t);
4556b700 3260 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
a87b802f 3261 return;
6be429b1
JB
3262
3263 case SIGQUIT:
a9f2c884 3264 tcgetattr (XINT (p->infd), &t);
4556b700 3265 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
a87b802f 3266 return;
6be429b1
JB
3267
3268 case SIGTSTP:
a9f2c884 3269 tcgetattr (XINT (p->infd), &t);
d0adf46f 3270#if defined (VSWTCH) && !defined (PREFER_VSUSP)
4556b700 3271 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6be429b1 3272#else
4556b700 3273 send_process (proc, &t.c_cc[VSUSP], 1, Qnil);
6be429b1 3274#endif
a87b802f 3275 return;
6be429b1
JB
3276 }
3277
3278#else /* ! HAVE_TERMIOS */
3279
b0310da4
JB
3280 /* On Berkeley descendants, the following IOCTL's retrieve the
3281 current control characters. */
d0d6b7c5 3282#if defined (TIOCGLTC) && defined (TIOCGETC)
b0310da4 3283
d0d6b7c5
JB
3284 struct tchars c;
3285 struct ltchars lc;
3286
3287 switch (signo)
3288 {
3289 case SIGINT:
a9f2c884 3290 ioctl (XINT (p->infd), TIOCGETC, &c);
4556b700 3291 send_process (proc, &c.t_intrc, 1, Qnil);
f9738840 3292 return;
d0d6b7c5 3293 case SIGQUIT:
a9f2c884 3294 ioctl (XINT (p->infd), TIOCGETC, &c);
4556b700 3295 send_process (proc, &c.t_quitc, 1, Qnil);
f9738840 3296 return;
0ad77c54 3297#ifdef SIGTSTP
d0d6b7c5 3298 case SIGTSTP:
a9f2c884 3299 ioctl (XINT (p->infd), TIOCGLTC, &lc);
4556b700 3300 send_process (proc, &lc.t_suspc, 1, Qnil);
f9738840 3301 return;
b0310da4 3302#endif /* ! defined (SIGTSTP) */
d0d6b7c5 3303 }
b0310da4
JB
3304
3305#else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
3306
3307 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
3308 characters. */
3309#ifdef TCGETA
d0d6b7c5
JB
3310 struct termio t;
3311 switch (signo)
3312 {
3313 case SIGINT:
a9f2c884 3314 ioctl (XINT (p->infd), TCGETA, &t);
4556b700 3315 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
f9738840 3316 return;
d0d6b7c5 3317 case SIGQUIT:
a9f2c884 3318 ioctl (XINT (p->infd), TCGETA, &t);
4556b700 3319 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
f9738840 3320 return;
7d79e3b4 3321#ifdef SIGTSTP
d0d6b7c5 3322 case SIGTSTP:
a9f2c884 3323 ioctl (XINT (p->infd), TCGETA, &t);
4556b700 3324 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
f9738840 3325 return;
b0310da4 3326#endif /* ! defined (SIGTSTP) */
d0d6b7c5 3327 }
b0310da4
JB
3328#else /* ! defined (TCGETA) */
3329 Your configuration files are messed up.
3330 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
3331 you'd better be using one of the alternatives above! */
3332#endif /* ! defined (TCGETA) */
3333#endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6be429b1 3334#endif /* ! defined HAVE_TERMIOS */
b0310da4 3335#endif /* ! defined (SIGNALS_VIA_CHARACTERS) */
d0d6b7c5 3336
301c3fe4 3337#ifdef TIOCGPGRP
d0d6b7c5
JB
3338 /* Get the pgrp using the tty itself, if we have that.
3339 Otherwise, use the pty to get the pgrp.
3340 On pfa systems, saka@pfu.fujitsu.co.JP writes:
b0310da4
JB
3341 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
3342 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
d0d6b7c5
JB
3343 His patch indicates that if TIOCGPGRP returns an error, then
3344 we should just assume that p->pid is also the process group id. */
3345 {
3346 int err;
3347
3348 if (!NILP (p->subtty))
3349 err = ioctl (XFASTINT (p->subtty), TIOCGPGRP, &gid);
3350 else
a9f2c884 3351 err = ioctl (XINT (p->infd), TIOCGPGRP, &gid);
d0d6b7c5
JB
3352
3353#ifdef pfa
3354 if (err == -1)
3355 gid = - XFASTINT (p->pid);
301c3fe4 3356#endif /* ! defined (pfa) */
d0d6b7c5
JB
3357 }
3358 if (gid == -1)
3359 no_pgrp = 1;
3360 else
3361 gid = - gid;
b0310da4 3362#else /* ! defined (TIOCGPGRP ) */
301c3fe4
JB
3363 /* Can't select pgrps on this system, so we know that
3364 the child itself heads the pgrp. */
3365 gid = - XFASTINT (p->pid);
3366#endif /* ! defined (TIOCGPGRP ) */
d0d6b7c5
JB
3367 }
3368 else
3369 gid = - XFASTINT (p->pid);
d0d6b7c5
JB
3370
3371 switch (signo)
3372 {
3373#ifdef SIGCONT
3374 case SIGCONT:
3375 p->raw_status_low = Qnil;
3376 p->raw_status_high = Qnil;
3377 p->status = Qrun;
3378 XSETINT (p->tick, ++process_tick);
3379 if (!nomsg)
3380 status_notify ();
3381 break;
301c3fe4 3382#endif /* ! defined (SIGCONT) */
d0d6b7c5
JB
3383 case SIGINT:
3384#ifdef VMS
4556b700 3385 send_process (proc, "\003", 1, Qnil); /* ^C */
d0d6b7c5
JB
3386 goto whoosh;
3387#endif
3388 case SIGQUIT:
3389#ifdef VMS
4556b700 3390 send_process (proc, "\031", 1, Qnil); /* ^Y */
d0d6b7c5
JB
3391 goto whoosh;
3392#endif
3393 case SIGKILL:
3394#ifdef VMS
3395 sys$forcex (&(XFASTINT (p->pid)), 0, 1);
3396 whoosh:
3397#endif
a9f2c884 3398 flush_pending_output (XINT (p->infd));
d0d6b7c5
JB
3399 break;
3400 }
3401
3402 /* If we don't have process groups, send the signal to the immediate
3403 subprocess. That isn't really right, but it's better than any
3404 obvious alternative. */
3405 if (no_pgrp)
3406 {
3407 kill (XFASTINT (p->pid), signo);
3408 return;
3409 }
3410
3411 /* gid may be a pid, or minus a pgrp's number */
3412#ifdef TIOCSIGSEND
3413 if (!NILP (current_group))
a9f2c884 3414 ioctl (XINT (p->infd), TIOCSIGSEND, signo);
d0d6b7c5
JB
3415 else
3416 {
3417 gid = - XFASTINT (p->pid);
3418 kill (gid, signo);
3419 }
301c3fe4 3420#else /* ! defined (TIOCSIGSEND) */
d0d6b7c5 3421 EMACS_KILLPG (-gid, signo);
301c3fe4 3422#endif /* ! defined (TIOCSIGSEND) */
d0d6b7c5
JB
3423}
3424
3425DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
3426 "Interrupt process PROCESS. May be process or name of one.\n\
ebb9e16f 3427PROCESS may be a process, a buffer, or the name of a process or buffer.\n\
e333e864 3428nil or no arg means current buffer's process.\n\
d0d6b7c5
JB
3429Second arg CURRENT-GROUP non-nil means send signal to\n\
3430the current process-group of the process's controlling terminal\n\
3431rather than to the process's own process group.\n\
3432If the process is a shell, this means interrupt current subjob\n\
3433rather than the shell.")
3434 (process, current_group)
3435 Lisp_Object process, current_group;
3436{
3437 process_send_signal (process, SIGINT, current_group, 0);
3438 return process;
3439}
3440
3441DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
3442 "Kill process PROCESS. May be process or name of one.\n\
3443See function `interrupt-process' for more details on usage.")
3444 (process, current_group)
3445 Lisp_Object process, current_group;
3446{
3447 process_send_signal (process, SIGKILL, current_group, 0);
3448 return process;
3449}
3450
3451DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
3452 "Send QUIT signal to process PROCESS. May be process or name of one.\n\
3453See function `interrupt-process' for more details on usage.")
3454 (process, current_group)
3455 Lisp_Object process, current_group;
3456{
3457 process_send_signal (process, SIGQUIT, current_group, 0);
3458 return process;
3459}
3460
3461DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
3462 "Stop process PROCESS. May be process or name of one.\n\
3463See function `interrupt-process' for more details on usage.")
3464 (process, current_group)
3465 Lisp_Object process, current_group;
3466{
3467#ifndef SIGTSTP
3468 error ("no SIGTSTP support");
3469#else
3470 process_send_signal (process, SIGTSTP, current_group, 0);
3471#endif
3472 return process;
3473}
3474
3475DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
3476 "Continue process PROCESS. May be process or name of one.\n\
3477See function `interrupt-process' for more details on usage.")
3478 (process, current_group)
3479 Lisp_Object process, current_group;
3480{
3481#ifdef SIGCONT
3482 process_send_signal (process, SIGCONT, current_group, 0);
3483#else
3484 error ("no SIGCONT support");
3485#endif
3486 return process;
3487}
3488
3489DEFUN ("signal-process", Fsignal_process, Ssignal_process,
3490 2, 2, "nProcess number: \nnSignal code: ",
4766242d
RS
3491 "Send the process with process id PID the signal with code SIGCODE.\n\
3492PID must be an integer. The process need not be a child of this Emacs.\n\
3493SIGCODE may be an integer, or a symbol whose name is a signal name.")
3494 (pid, sigcode)
3495 Lisp_Object pid, sigcode;
d0d6b7c5
JB
3496{
3497 CHECK_NUMBER (pid, 0);
4766242d
RS
3498
3499#define handle_signal(NAME, VALUE) \
3500 else if (!strcmp (name, NAME)) \
3501 XSETINT (sigcode, VALUE)
3502
3503 if (INTEGERP (sigcode))
3504 ;
3505 else
3506 {
3507 unsigned char *name;
3508
3509 CHECK_SYMBOL (sigcode, 1);
3510 name = XSYMBOL (sigcode)->name->data;
3511
3512 if (0)
3513 ;
3514#ifdef SIGHUP
3515 handle_signal ("SIGHUP", SIGHUP);
3516#endif
3517#ifdef SIGINT
3518 handle_signal ("SIGINT", SIGINT);
3519#endif
3520#ifdef SIGQUIT
3521 handle_signal ("SIGQUIT", SIGQUIT);
3522#endif
3523#ifdef SIGILL
3524 handle_signal ("SIGILL", SIGILL);
3525#endif
3526#ifdef SIGABRT
3527 handle_signal ("SIGABRT", SIGABRT);
3528#endif
3529#ifdef SIGEMT
3530 handle_signal ("SIGEMT", SIGEMT);
3531#endif
3532#ifdef SIGKILL
3533 handle_signal ("SIGKILL", SIGKILL);
3534#endif
3535#ifdef SIGFPE
3536 handle_signal ("SIGFPE", SIGFPE);
3537#endif
3538#ifdef SIGBUS
3539 handle_signal ("SIGBUS", SIGBUS);
3540#endif
3541#ifdef SIGSEGV
3542 handle_signal ("SIGSEGV", SIGSEGV);
3543#endif
3544#ifdef SIGSYS
3545 handle_signal ("SIGSYS", SIGSYS);
3546#endif
3547#ifdef SIGPIPE
3548 handle_signal ("SIGPIPE", SIGPIPE);
3549#endif
3550#ifdef SIGALRM
3551 handle_signal ("SIGALRM", SIGALRM);
3552#endif
3553#ifdef SIGTERM
3554 handle_signal ("SIGTERM", SIGTERM);
3555#endif
3556#ifdef SIGURG
3557 handle_signal ("SIGURG", SIGURG);
3558#endif
3559#ifdef SIGSTOP
3560 handle_signal ("SIGSTOP", SIGSTOP);
3561#endif
3562#ifdef SIGTSTP
3563 handle_signal ("SIGTSTP", SIGTSTP);
3564#endif
3565#ifdef SIGCONT
3566 handle_signal ("SIGCONT", SIGCONT);
3567#endif
3568#ifdef SIGCHLD
3569 handle_signal ("SIGCHLD", SIGCHLD);
3570#endif
3571#ifdef SIGTTIN
3572 handle_signal ("SIGTTIN", SIGTTIN);
3573#endif
3574#ifdef SIGTTOU
3575 handle_signal ("SIGTTOU", SIGTTOU);
3576#endif
3577#ifdef SIGIO
3578 handle_signal ("SIGIO", SIGIO);
3579#endif
3580#ifdef SIGXCPU
3581 handle_signal ("SIGXCPU", SIGXCPU);
3582#endif
3583#ifdef SIGXFSZ
3584 handle_signal ("SIGXFSZ", SIGXFSZ);
3585#endif
3586#ifdef SIGVTALRM
3587 handle_signal ("SIGVTALRM", SIGVTALRM);
3588#endif
3589#ifdef SIGPROF
3590 handle_signal ("SIGPROF", SIGPROF);
3591#endif
3592#ifdef SIGWINCH
3593 handle_signal ("SIGWINCH", SIGWINCH);
3594#endif
3595#ifdef SIGINFO
3596 handle_signal ("SIGINFO", SIGINFO);
3597#endif
3598#ifdef SIGUSR1
3599 handle_signal ("SIGUSR1", SIGUSR1);
3600#endif
3601#ifdef SIGUSR2
3602 handle_signal ("SIGUSR2", SIGUSR2);
3603#endif
3604 else
9fa195a2 3605 error ("Undefined signal name %s", name);
4766242d
RS
3606 }
3607
3608#undef handle_signal
3609
4766242d 3610 return make_number (kill (XINT (pid), XINT (sigcode)));
d0d6b7c5
JB
3611}
3612
3613DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
3614 "Make PROCESS see end-of-file in its input.\n\
3615Eof comes after any text already sent to it.\n\
ebb9e16f 3616PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
d33a00f2
RS
3617nil, indicating the current buffer's process.\n\
3618If PROCESS is a network connection, or is a process communicating\n\
3619through a pipe (as opposed to a pty), then you cannot send any more\n\
3620text to PROCESS after you call this function.")
d0d6b7c5
JB
3621 (process)
3622 Lisp_Object process;
3623{
3624 Lisp_Object proc;
3625
3626 proc = get_process (process);
577d03d5
RS
3627
3628 /* Make sure the process is really alive. */
3629 if (! NILP (XPROCESS (proc)->raw_status_low))
3630 update_status (XPROCESS (proc));
3631 if (! EQ (XPROCESS (proc)->status, Qrun))
dcf970e6 3632 error ("Process %s not running", XSTRING (XPROCESS (proc)->name)->data);
577d03d5 3633
d0d6b7c5 3634#ifdef VMS
4556b700 3635 send_process (proc, "\032", 1, Qnil); /* ^z */
d0d6b7c5
JB
3636#else
3637 if (!NILP (XPROCESS (proc)->pty_flag))
4556b700 3638 send_process (proc, "\004", 1, Qnil);
d0d6b7c5
JB
3639 else
3640 {
93853f3d 3641#ifdef HAVE_SHUTDOWN
02f55c4b
RS
3642 /* If this is a network connection, or socketpair is used
3643 for communication with the subprocess, call shutdown to cause EOF.
3644 (In some old system, shutdown to socketpair doesn't work.
3645 Then we just can't win.) */
3646 if (NILP (XPROCESS (proc)->pid)
3647 || XINT (XPROCESS (proc)->outfd) == XINT (XPROCESS (proc)->infd))
3648 shutdown (XINT (XPROCESS (proc)->outfd), 1);
3649 /* In case of socketpair, outfd == infd, so don't close it. */
3650 if (XINT (XPROCESS (proc)->outfd) != XINT (XPROCESS (proc)->infd))
3651 close (XINT (XPROCESS (proc)->outfd));
93853f3d
RS
3652#else /* not HAVE_SHUTDOWN */
3653 close (XINT (XPROCESS (proc)->outfd));
3654#endif /* not HAVE_SHUTDOWN */
1d056e64 3655 XSETINT (XPROCESS (proc)->outfd, open (NULL_DEVICE, O_WRONLY));
d0d6b7c5
JB
3656 }
3657#endif /* VMS */
d0d6b7c5
JB
3658 return process;
3659}
3660
3661/* Kill all processes associated with `buffer'.
3662 If `buffer' is nil, kill all processes */
3663
3664kill_buffer_processes (buffer)
3665 Lisp_Object buffer;
3666{
3667 Lisp_Object tail, proc;
3668
b5b502d6 3669 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCONS (tail)->cdr)
d0d6b7c5
JB
3670 {
3671 proc = XCONS (XCONS (tail)->car)->cdr;
b5b502d6 3672 if (GC_PROCESSP (proc)
d0d6b7c5
JB
3673 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
3674 {
3675 if (NETCONN_P (proc))
e1ab4959 3676 Fdelete_process (proc);
a9f2c884 3677 else if (XINT (XPROCESS (proc)->infd) >= 0)
d0d6b7c5
JB
3678 process_send_signal (proc, SIGHUP, Qnil, 1);
3679 }
3680 }
3681}
3682\f
3683/* On receipt of a signal that a child status has changed,
3684 loop asking about children with changed statuses until
3685 the system says there are no more.
3686 All we do is change the status;
3687 we do not run sentinels or print notifications.
3688 That is saved for the next time keyboard input is done,
3689 in order to avoid timing errors. */
3690
3691/** WARNING: this can be called during garbage collection.
3692 Therefore, it must not be fooled by the presence of mark bits in
3693 Lisp objects. */
3694
3695/** USG WARNING: Although it is not obvious from the documentation
3696 in signal(2), on a USG system the SIGCLD handler MUST NOT call
3697 signal() before executing at least one wait(), otherwise the handler
3698 will be called again, resulting in an infinite loop. The relevant
3699 portion of the documentation reads "SIGCLD signals will be queued
3700 and the signal-catching function will be continually reentered until
3701 the queue is empty". Invoking signal() causes the kernel to reexamine
3702 the SIGCLD queue. Fred Fish, UniSoft Systems Inc. */
3703
3704SIGTYPE
3705sigchld_handler (signo)
3706 int signo;
3707{
3708 int old_errno = errno;
3709 Lisp_Object proc;
3710 register struct Lisp_Process *p;
6be429b1 3711 extern EMACS_TIME *input_available_clear_time;
d0d6b7c5
JB
3712
3713#ifdef BSD4_1
3714 extern int sigheld;
3715 sigheld |= sigbit (SIGCHLD);
3716#endif
3717
3718 while (1)
3719 {
3720 register int pid;
3721 WAITTYPE w;
3722 Lisp_Object tail;
3723
3724#ifdef WNOHANG
3725#ifndef WUNTRACED
3726#define WUNTRACED 0
3727#endif /* no WUNTRACED */
3728 /* Keep trying to get a status until we get a definitive result. */
3729 do
3730 {
3731 errno = 0;
3732 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
3733 }
3734 while (pid <= 0 && errno == EINTR);
3735
3736 if (pid <= 0)
3737 {
3738 /* A real failure. We have done all our job, so return. */
3739
3740 /* USG systems forget handlers when they are used;
3741 must reestablish each time */
3c0ee47b 3742#if defined (USG) && !defined (POSIX_SIGNALS)
d0d6b7c5
JB
3743 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
3744#endif
3745#ifdef BSD4_1
3746 sigheld &= ~sigbit (SIGCHLD);
3747 sigrelse (SIGCHLD);
3748#endif
3749 errno = old_errno;
3750 return;
3751 }
3752#else
3753 pid = wait (&w);
3754#endif /* no WNOHANG */
3755
3756 /* Find the process that signaled us, and record its status. */
3757
3758 p = 0;
7968cc2d 3759 for (tail = Vprocess_alist; CONSP (tail); tail = XCONS (tail)->cdr)
d0d6b7c5
JB
3760 {
3761 proc = XCONS (XCONS (tail)->car)->cdr;
3762 p = XPROCESS (proc);
3763 if (EQ (p->childp, Qt) && XFASTINT (p->pid) == pid)
3764 break;
3765 p = 0;
3766 }
3767
3768 /* Look for an asynchronous process whose pid hasn't been filled
3769 in yet. */
3770 if (p == 0)
7968cc2d 3771 for (tail = Vprocess_alist; CONSP (tail); tail = XCONS (tail)->cdr)
d0d6b7c5
JB
3772 {
3773 proc = XCONS (XCONS (tail)->car)->cdr;
3774 p = XPROCESS (proc);
bcd69aea 3775 if (INTEGERP (p->pid) && XINT (p->pid) == -1)
d0d6b7c5
JB
3776 break;
3777 p = 0;
3778 }
3779
3780 /* Change the status of the process that was found. */
3781 if (p != 0)
3782 {
3783 union { int i; WAITTYPE wt; } u;
e98d950b 3784 int clear_desc_flag = 0;
d0d6b7c5
JB
3785
3786 XSETINT (p->tick, ++process_tick);
3787 u.wt = w;
5fc0154c
RS
3788 XSETINT (p->raw_status_low, u.i & 0xffff);
3789 XSETINT (p->raw_status_high, u.i >> 16);
d0d6b7c5
JB
3790
3791 /* If process has terminated, stop waiting for its output. */
e98d950b
RS
3792 if ((WIFSIGNALED (w) || WIFEXITED (w))
3793 && XINT (p->infd) >= 0)
3794 clear_desc_flag = 1;
3795
3796 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
3797 if (clear_desc_flag)
3798 {
3799 FD_CLR (XINT (p->infd), &input_wait_mask);
3800 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
3801 }
6be429b1
JB
3802
3803 /* Tell wait_reading_process_input that it needs to wake up and
3804 look around. */
3805 if (input_available_clear_time)
3806 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
d0d6b7c5
JB
3807 }
3808
3809 /* There was no asynchronous process found for that id. Check
3810 if we have a synchronous process. */
3811 else
3812 {
3813 synch_process_alive = 0;
3814
3815 /* Report the status of the synchronous process. */
3816 if (WIFEXITED (w))
3817 synch_process_retcode = WRETCODE (w);
3818 else if (WIFSIGNALED (w))
b97ad9ea
RS
3819 {
3820 int code = WTERMSIG (w);
3821 char *signame = 0;
3822
3823 if (code < NSIG)
3824 {
b0310da4 3825#ifndef VMS
ed0cae05
RS
3826 /* Suppress warning if the table has const char *. */
3827 signame = (char *) sys_siglist[code];
b0310da4 3828#else
b97ad9ea 3829 signame = sys_errlist[code];
b0310da4 3830#endif
b97ad9ea
RS
3831 }
3832 if (signame == 0)
3833 signame = "unknown";
3834
3835 synch_process_death = signame;
3836 }
6be429b1
JB
3837
3838 /* Tell wait_reading_process_input that it needs to wake up and
3839 look around. */
3840 if (input_available_clear_time)
3841 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
d0d6b7c5
JB
3842 }
3843
3844 /* On some systems, we must return right away.
3845 If any more processes want to signal us, we will
3846 get another signal.
3847 Otherwise (on systems that have WNOHANG), loop around
3848 to use up all the processes that have something to tell us. */
e98d950b 3849#if defined (USG) && ! (defined (HPUX) && defined (WNOHANG)) || defined (WINDOWSNT)
3c0ee47b 3850#if defined (USG) && ! defined (POSIX_SIGNALS)
d0d6b7c5
JB
3851 signal (signo, sigchld_handler);
3852#endif
3853 errno = old_errno;
3854 return;
3855#endif /* USG, but not HPUX with WNOHANG */
3856 }
3857}
3858\f
3859
3860static Lisp_Object
3861exec_sentinel_unwind (data)
3862 Lisp_Object data;
3863{
3864 XPROCESS (XCONS (data)->car)->sentinel = XCONS (data)->cdr;
3865 return Qnil;
3866}
3867
3b9a3dfa
RS
3868static Lisp_Object
3869exec_sentinel_error_handler (error)
3870 Lisp_Object error;
3871{
3872 cmd_error_internal (error, "error in process sentinel: ");
3873 Vinhibit_quit = Qt;
3874 update_echo_area ();
833ba342 3875 Fsleep_for (make_number (2), Qnil);
3b9a3dfa
RS
3876}
3877
d0d6b7c5
JB
3878static void
3879exec_sentinel (proc, reason)
3880 Lisp_Object proc, reason;
3881{
dfc21838 3882 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
d0d6b7c5
JB
3883 register struct Lisp_Process *p = XPROCESS (proc);
3884 int count = specpdl_ptr - specpdl;
4da2f5be 3885 int outer_running_asynch_code = running_asynch_code;
d0d6b7c5 3886
dfc21838
RS
3887 /* No need to gcpro these, because all we do with them later
3888 is test them for EQness, and none of them should be a string. */
8fb3cf64 3889 odeactivate = Vdeactivate_mark;
dfc21838
RS
3890 XSETBUFFER (obuffer, current_buffer);
3891 okeymap = current_buffer->keymap;
3892
d0d6b7c5
JB
3893 sentinel = p->sentinel;
3894 if (NILP (sentinel))
3895 return;
3896
3897 /* Zilch the sentinel while it's running, to avoid recursive invocations;
3898 assure that it gets restored no matter how the sentinel exits. */
3899 p->sentinel = Qnil;
3900 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
3901 /* Inhibit quit so that random quits don't screw up a running filter. */
3902 specbind (Qinhibit_quit, Qt);
6545aada 3903 specbind (Qlast_nonmenu_event, Qt);
3b9a3dfa 3904
4da2f5be
RS
3905 /* In case we get recursively called,
3906 and we already saved the match data nonrecursively,
3907 save the same match data in safely recursive fashion. */
3908 if (outer_running_asynch_code)
3909 {
3910 Lisp_Object tem;
dd130227 3911 tem = Fmatch_data (Qnil, Qnil);
4da2f5be 3912 restore_match_data ();
dd130227 3913 record_unwind_protect (Fstore_match_data, Fmatch_data (Qnil, Qnil));
4da2f5be
RS
3914 Fstore_match_data (tem);
3915 }
3916
3917 /* For speed, if a search happens within this code,
3918 save the match data in a special nonrecursive fashion. */
7074fde6 3919 running_asynch_code = 1;
4da2f5be 3920
3b9a3dfa
RS
3921 internal_condition_case_1 (read_process_output_call,
3922 Fcons (sentinel,
3923 Fcons (proc, Fcons (reason, Qnil))),
3924 !NILP (Vdebug_on_error) ? Qnil : Qerror,
3925 exec_sentinel_error_handler);
4da2f5be
RS
3926
3927 /* If we saved the match data nonrecursively, restore it now. */
7074fde6 3928 restore_match_data ();
4da2f5be 3929 running_asynch_code = outer_running_asynch_code;
8fb3cf64
KH
3930
3931 Vdeactivate_mark = odeactivate;
7973cfa8 3932#if 0
dfc21838
RS
3933 if (! EQ (Fcurrent_buffer (), obuffer)
3934 || ! EQ (current_buffer->keymap, okeymap))
7973cfa8 3935#endif
927e08be
RS
3936 /* But do it only if the caller is actually going to read events.
3937 Otherwise there's no need to make him wake up, and it could
3938 cause trouble (for example it would make Fsit_for return). */
3939 if (waiting_for_user_input_p == -1)
3940 record_asynch_buffer_change ();
8fb3cf64 3941
2ea6d561 3942 unbind_to (count, Qnil);
d0d6b7c5
JB
3943}
3944
3945/* Report all recent events of a change in process status
3946 (either run the sentinel or output a message).
3947 This is done while Emacs is waiting for keyboard input. */
3948
3949status_notify ()
3950{
3951 register Lisp_Object proc, buffer;
2e4149a8 3952 Lisp_Object tail, msg;
d0d6b7c5
JB
3953 struct gcpro gcpro1, gcpro2;
3954
2e4149a8
KH
3955 tail = Qnil;
3956 msg = Qnil;
d0d6b7c5
JB
3957 /* We need to gcpro tail; if read_process_output calls a filter
3958 which deletes a process and removes the cons to which tail points
3959 from Vprocess_alist, and then causes a GC, tail is an unprotected
3960 reference. */
3961 GCPRO2 (tail, msg);
3962
30623085
RS
3963 /* Set this now, so that if new processes are created by sentinels
3964 that we run, we get called again to handle their status changes. */
3965 update_tick = process_tick;
3966
3967 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
d0d6b7c5 3968 {
30623085
RS
3969 Lisp_Object symbol;
3970 register struct Lisp_Process *p;
3971
3972 proc = Fcdr (Fcar (tail));
3973 p = XPROCESS (proc);
3974
3975 if (XINT (p->tick) != XINT (p->update_tick))
d0d6b7c5 3976 {
30623085 3977 XSETINT (p->update_tick, XINT (p->tick));
d0d6b7c5 3978
30623085 3979 /* If process is still active, read any output that remains. */
4da2f5be
RS
3980 while (! EQ (p->filter, Qt)
3981 && XINT (p->infd) >= 0
3982 && read_process_output (proc, XINT (p->infd)) > 0);
d0d6b7c5 3983
30623085 3984 buffer = p->buffer;
d0d6b7c5 3985
30623085
RS
3986 /* Get the text to use for the message. */
3987 if (!NILP (p->raw_status_low))
3988 update_status (p);
3989 msg = status_message (p->status);
d0d6b7c5 3990
30623085
RS
3991 /* If process is terminated, deactivate it or delete it. */
3992 symbol = p->status;
3993 if (CONSP (p->status))
3994 symbol = XCONS (p->status)->car;
d0d6b7c5 3995
30623085
RS
3996 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
3997 || EQ (symbol, Qclosed))
3998 {
3999 if (delete_exited_processes)
4000 remove_process (proc);
4001 else
4002 deactivate_process (proc);
4003 }
d0d6b7c5 4004
0ad61fe7
RS
4005 /* The actions above may have further incremented p->tick.
4006 So set p->update_tick again
4007 so that an error in the sentinel will not cause
4008 this code to be run again. */
4009 XSETINT (p->update_tick, XINT (p->tick));
30623085
RS
4010 /* Now output the message suitably. */
4011 if (!NILP (p->sentinel))
4012 exec_sentinel (proc, msg);
4013 /* Don't bother with a message in the buffer
4014 when a process becomes runnable. */
4015 else if (!EQ (symbol, Qrun) && !NILP (buffer))
4016 {
4017 Lisp_Object ro, tem;
4018 struct buffer *old = current_buffer;
4019 int opoint;
12ca5cdf 4020 int before;
2e4149a8 4021
30623085 4022 ro = XBUFFER (buffer)->read_only;
d0d6b7c5 4023
30623085
RS
4024 /* Avoid error if buffer is deleted
4025 (probably that's why the process is dead, too) */
4026 if (NILP (XBUFFER (buffer)->name))
4027 continue;
4028 Fset_buffer (buffer);
12ca5cdf 4029
6ec8bbd2 4030 opoint = PT;
30623085
RS
4031 /* Insert new output into buffer
4032 at the current end-of-output marker,
4033 thus preserving logical ordering of input and output. */
4034 if (XMARKER (p->mark)->buffer)
4035 SET_PT (marker_position (p->mark));
4036 else
4037 SET_PT (ZV);
12ca5cdf
RS
4038
4039 before = PT;
30623085
RS
4040
4041 tem = current_buffer->read_only;
4042 current_buffer->read_only = Qnil;
4043 insert_string ("\nProcess ");
4044 Finsert (1, &p->name);
4045 insert_string (" ");
4046 Finsert (1, &msg);
4047 current_buffer->read_only = tem;
6ec8bbd2 4048 Fset_marker (p->mark, make_number (PT), p->buffer);
30623085 4049
12ca5cdf
RS
4050 if (opoint >= before)
4051 SET_PT (opoint + (PT - before));
4052 else
4053 SET_PT (opoint);
4054
30623085 4055 set_buffer_internal (old);
d0d6b7c5 4056 }
30623085
RS
4057 }
4058 } /* end for */
d0d6b7c5
JB
4059
4060 update_mode_lines++; /* in case buffers use %s in mode-line-format */
4061 redisplay_preserve_echo_area ();
4062
d0d6b7c5
JB
4063 UNGCPRO;
4064}
0fa1789e
KH
4065
4066\f
4067DEFUN ("set-process-coding-system", Fset_process_coding_system,
4068 Sset_process_coding_system, 1, 3, 0,
4069 "Set coding-systems of PROCESS to DECODING (input from the process) and\n\
4070ENCODING (output to the process).")
4071 (proc, decoding, encoding)
4072 register Lisp_Object proc, decoding, encoding;
4073{
4074 register struct Lisp_Process *p;
4075
4076 CHECK_PROCESS (proc, 0);
4077 p = XPROCESS (proc);
4078 if (XINT (p->infd) < 0)
4079 error ("Input file descriptor of %s closed", XSTRING (p->name)->data);
4080 if (XINT (p->outfd) < 0)
4081 error ("Output file descriptor of %s closed", XSTRING (p->name)->data);
4082
4083 p->decode_coding_system = Fcheck_coding_system (decoding);
4084 p->encode_coding_system = Fcheck_coding_system (encoding);
4085 setup_coding_system (decoding,
c7580538 4086 proc_decode_coding_system[XINT (p->infd)]);
0fa1789e 4087 setup_coding_system (encoding,
c7580538 4088 proc_encode_coding_system[XINT (p->outfd)]);
0fa1789e
KH
4089
4090 return Qnil;
4091}
4092
4093DEFUN ("process-coding-system",
4094 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
4095 "Return a cons of coding-system for decoding and encoding of PROCESS.")
4096 (proc)
4097 register Lisp_Object proc;
4098{
4099 CHECK_PROCESS (proc, 0);
4100 return Fcons (XPROCESS (proc)->decode_coding_system,
4101 XPROCESS (proc)->encode_coding_system);
4102}
d0d6b7c5 4103\f
a69281ff
RS
4104/* The first time this is called, assume keyboard input comes from DESC
4105 instead of from where we used to expect it.
4106 Subsequent calls mean assume input keyboard can come from DESC
4107 in addition to other places. */
4108
4109static int add_keyboard_wait_descriptor_called_flag;
4110
4111void
4112add_keyboard_wait_descriptor (desc)
4113 int desc;
4114{
4115 if (! add_keyboard_wait_descriptor_called_flag)
4116 FD_CLR (0, &input_wait_mask);
4117 add_keyboard_wait_descriptor_called_flag = 1;
4118 FD_SET (desc, &input_wait_mask);
b5dc1c83 4119 FD_SET (desc, &non_process_wait_mask);
a69281ff
RS
4120 if (desc > max_keyboard_desc)
4121 max_keyboard_desc = desc;
4122}
4123
4124/* From now on, do not expect DESC to give keyboard input. */
4125
4126void
4127delete_keyboard_wait_descriptor (desc)
4128 int desc;
4129{
4130 int fd;
4131 int lim = max_keyboard_desc;
4132
4133 FD_CLR (desc, &input_wait_mask);
b5dc1c83 4134 FD_CLR (desc, &non_process_wait_mask);
a69281ff
RS
4135
4136 if (desc == max_keyboard_desc)
4137 for (fd = 0; fd < lim; fd++)
4138 if (FD_ISSET (fd, &input_wait_mask)
4139 && !FD_ISSET (fd, &non_keyboard_wait_mask))
4140 max_keyboard_desc = fd;
4141}
4142
4143/* Return nonzero if *MASK has a bit set
4144 that corresponds to one of the keyboard input descriptors. */
4145
4146int
4147keyboard_bit_set (mask)
4148 SELECT_TYPE *mask;
4149{
4150 int fd;
4151
ee8e09af 4152 for (fd = 0; fd <= max_keyboard_desc; fd++)
a69281ff
RS
4153 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
4154 && !FD_ISSET (fd, &non_keyboard_wait_mask))
4155 return 1;
4156
4157 return 0;
4158}
4159\f
d0d6b7c5
JB
4160init_process ()
4161{
4162 register int i;
4163
4164#ifdef SIGCHLD
4165#ifndef CANNOT_DUMP
4166 if (! noninteractive || initialized)
4167#endif
4168 signal (SIGCHLD, sigchld_handler);
4169#endif
4170
4171 FD_ZERO (&input_wait_mask);
a69281ff 4172 FD_ZERO (&non_keyboard_wait_mask);
b5dc1c83 4173 FD_ZERO (&non_process_wait_mask);
7d0e672e 4174 max_process_desc = 0;
dd2281ae 4175
a69281ff 4176 FD_SET (0, &input_wait_mask);
dd2281ae 4177
d0d6b7c5
JB
4178 Vprocess_alist = Qnil;
4179 for (i = 0; i < MAXDESC; i++)
4180 {
4181 chan_process[i] = Qnil;
4182 proc_buffered_char[i] = -1;
4183 }
c7580538
KH
4184 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
4185 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
d0d6b7c5 4186}
312c9964 4187
d0d6b7c5
JB
4188syms_of_process ()
4189{
d0d6b7c5
JB
4190 Qprocessp = intern ("processp");
4191 staticpro (&Qprocessp);
4192 Qrun = intern ("run");
4193 staticpro (&Qrun);
4194 Qstop = intern ("stop");
4195 staticpro (&Qstop);
4196 Qsignal = intern ("signal");
4197 staticpro (&Qsignal);
4198
4199 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
4200 here again.
4201
4202 Qexit = intern ("exit");
4203 staticpro (&Qexit); */
4204
4205 Qopen = intern ("open");
4206 staticpro (&Qopen);
4207 Qclosed = intern ("closed");
4208 staticpro (&Qclosed);
4209
6545aada
RS
4210 Qlast_nonmenu_event = intern ("last-nonmenu-event");
4211 staticpro (&Qlast_nonmenu_event);
4212
d0d6b7c5
JB
4213 staticpro (&Vprocess_alist);
4214
4215 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
4216 "*Non-nil means delete processes immediately when they exit.\n\
4217nil means don't delete them until `list-processes' is run.");
4218
4219 delete_exited_processes = 1;
4220
4221 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
4222 "Control type of device used to communicate with subprocesses.\n\
e333e864
RS
4223Values are nil to use a pipe, or t or `pty' to use a pty.\n\
4224The value has no effect if the system has no ptys or if all ptys are busy:\n\
4225then a pipe is used in any case.\n\
4226The value takes effect when `start-process' is called.");
d0d6b7c5
JB
4227 Vprocess_connection_type = Qt;
4228
4229 defsubr (&Sprocessp);
4230 defsubr (&Sget_process);
4231 defsubr (&Sget_buffer_process);
4232 defsubr (&Sdelete_process);
4233 defsubr (&Sprocess_status);
4234 defsubr (&Sprocess_exit_status);
4235 defsubr (&Sprocess_id);
4236 defsubr (&Sprocess_name);
3b9a3dfa 4237 defsubr (&Sprocess_tty_name);
d0d6b7c5
JB
4238 defsubr (&Sprocess_command);
4239 defsubr (&Sset_process_buffer);
4240 defsubr (&Sprocess_buffer);
4241 defsubr (&Sprocess_mark);
4242 defsubr (&Sset_process_filter);
4243 defsubr (&Sprocess_filter);
4244 defsubr (&Sset_process_sentinel);
4245 defsubr (&Sprocess_sentinel);
de282a05 4246 defsubr (&Sset_process_window_size);
d0d6b7c5 4247 defsubr (&Sprocess_kill_without_query);
de282a05 4248 defsubr (&Sprocess_contact);
d0d6b7c5
JB
4249 defsubr (&Slist_processes);
4250 defsubr (&Sprocess_list);
4251 defsubr (&Sstart_process);
4252#ifdef HAVE_SOCKETS
4253 defsubr (&Sopen_network_stream);
4254#endif /* HAVE_SOCKETS */
4255 defsubr (&Saccept_process_output);
4256 defsubr (&Sprocess_send_region);
4257 defsubr (&Sprocess_send_string);
4258 defsubr (&Sinterrupt_process);
4259 defsubr (&Skill_process);
4260 defsubr (&Squit_process);
4261 defsubr (&Sstop_process);
4262 defsubr (&Scontinue_process);
4263 defsubr (&Sprocess_send_eof);
4264 defsubr (&Ssignal_process);
4265 defsubr (&Swaiting_for_user_input_p);
4266/* defsubr (&Sprocess_connection); */
0fa1789e
KH
4267 defsubr (&Sset_process_coding_system);
4268 defsubr (&Sprocess_coding_system);
d0d6b7c5
JB
4269}
4270
6720a7fb
JB
4271\f
4272#else /* not subprocesses */
4273
4274#include <sys/types.h>
4275#include <errno.h>
4276
4277#include "lisp.h"
4278#include "systime.h"
4279#include "termopts.h"
81afb6d1 4280#include "sysselect.h"
6720a7fb 4281
ff11dfa1 4282extern int frame_garbaged;
6720a7fb 4283
f694e5d2
KH
4284extern EMACS_TIME timer_check ();
4285extern int timers_run;
6720a7fb
JB
4286
4287/* As described above, except assuming that there are no subprocesses:
4288
4289 Wait for timeout to elapse and/or keyboard input to be available.
4290
4291 time_limit is:
4292 timeout in seconds, or
4293 zero for no limit, or
4294 -1 means gobble data immediately available but don't wait for any.
4295
f76475ad 4296 read_kbd is a Lisp_Object:
6720a7fb
JB
4297 0 to ignore keyboard input, or
4298 1 to return when input is available, or
4299 -1 means caller will actually read the input, so don't throw to
4300 the quit handler.
0a65b032
RS
4301 a cons cell, meaning wait until its car is non-nil
4302 (and gobble terminal input into the buffer if any arrives), or
6720a7fb
JB
4303 We know that read_kbd will never be a Lisp_Process, since
4304 `subprocesses' isn't defined.
4305
4306 do_display != 0 means redisplay should be done to show subprocess
5164ee8e 4307 output that arrives.
6720a7fb 4308
eb8c3be9 4309 Return true iff we received input from any process. */
6720a7fb
JB
4310
4311int
4312wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
f76475ad
JB
4313 int time_limit, microsecs;
4314 Lisp_Object read_kbd;
4315 int do_display;
6720a7fb 4316{
f694e5d2 4317 EMACS_TIME end_time, timeout;
8db121c4 4318 SELECT_TYPE waitchannels;
f694e5d2 4319 int xerrno;
0a65b032
RS
4320 Lisp_Object *wait_for_cell = 0;
4321
4322 /* If waiting for non-nil in a cell, record where. */
4323 if (CONSP (read_kbd))
4324 {
4325 wait_for_cell = &XCONS (read_kbd)->car;
4326 XSETFASTINT (read_kbd, 0);
4327 }
6720a7fb
JB
4328
4329 /* What does time_limit really mean? */
4330 if (time_limit || microsecs)
4331 {
6720a7fb
JB
4332 if (time_limit == -1)
4333 /* In fact, it's zero. */
4334 EMACS_SET_SECS_USECS (timeout, 0, 0);
4335 else
4336 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4337
4338 /* How far in the future is that? */
4339 EMACS_GET_TIME (end_time);
4340 EMACS_ADD_TIME (end_time, end_time, timeout);
4341 }
4342 else
4343 /* It's infinite. */
f694e5d2 4344 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6720a7fb
JB
4345
4346 /* Turn off periodic alarms (in case they are in use)
4347 because the select emulator uses alarms. */
4348 stop_polling ();
4349
4350 for (;;)
4351 {
4352 int nfds;
bae8d137 4353 int timeout_reduced_for_timers = 0;
6720a7fb 4354
6720a7fb
JB
4355 /* If calling from keyboard input, do not quit
4356 since we want to return C-g as an input character.
4357 Otherwise, do pending quit if requested. */
f76475ad 4358 if (XINT (read_kbd) >= 0)
6720a7fb
JB
4359 QUIT;
4360
0a65b032
RS
4361 /* Exit now if the cell we're waiting for became non-nil. */
4362 if (wait_for_cell && ! NILP (*wait_for_cell))
4363 break;
4364
bae8d137
RS
4365 /* Compute time from now till when time limit is up */
4366 /* Exit if already run out */
f694e5d2 4367 if (time_limit > 0 || microsecs)
6720a7fb 4368 {
f694e5d2
KH
4369 EMACS_GET_TIME (timeout);
4370 EMACS_SUB_TIME (timeout, end_time, timeout);
4371 if (EMACS_TIME_NEG_P (timeout))
6720a7fb
JB
4372 break;
4373 }
4374
bae8d137
RS
4375 /* If our caller will not immediately handle keyboard events,
4376 run timer events directly.
4377 (Callers that will immediately read keyboard events
4378 call timer_delay on their own.) */
f854a00b 4379 if (! wait_for_cell)
bae8d137
RS
4380 {
4381 EMACS_TIME timer_delay;
0a65b032
RS
4382 int old_timers_run;
4383
4384 retry:
4385 old_timers_run = timers_run;
bae8d137
RS
4386 timer_delay = timer_check (1);
4387 if (timers_run != old_timers_run && do_display)
0a65b032
RS
4388 {
4389 redisplay_preserve_echo_area ();
4390 /* We must retry, since a timer may have requeued itself
4391 and that could alter the time delay. */
4392 goto retry;
4393 }
4394
f694e5d2 4395 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
bae8d137
RS
4396 {
4397 EMACS_TIME difference;
f694e5d2 4398 EMACS_SUB_TIME (difference, timer_delay, timeout);
bae8d137
RS
4399 if (EMACS_TIME_NEG_P (difference))
4400 {
f694e5d2 4401 timeout = timer_delay;
bae8d137
RS
4402 timeout_reduced_for_timers = 1;
4403 }
4404 }
4405 }
4406
6720a7fb
JB
4407 /* Cause C-g and alarm signals to take immediate action,
4408 and cause input available signals to zero out timeout. */
f76475ad 4409 if (XINT (read_kbd) < 0)
6720a7fb
JB
4410 set_waiting_for_input (&timeout);
4411
0a65b032
RS
4412 /* Wait till there is something to do. */
4413
4414 if (! XINT (read_kbd) && wait_for_cell == 0)
4415 FD_ZERO (&waitchannels);
4416 else
4417 FD_SET (0, &waitchannels);
4418
ff11dfa1 4419 /* If a frame has been newly mapped and needs updating,
6720a7fb 4420 reprocess its display stuff. */
5164ee8e 4421 if (frame_garbaged && do_display)
0a65b032
RS
4422 {
4423 clear_waiting_for_input ();
4424 redisplay_preserve_echo_area ();
4425 if (XINT (read_kbd) < 0)
4426 set_waiting_for_input (&timeout);
4427 }
6720a7fb 4428
1861b214
RS
4429 if (XINT (read_kbd) && detect_input_pending ())
4430 {
4431 nfds = 0;
4432 FD_ZERO (&waitchannels);
4433 }
4434 else
4435 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4436 &timeout);
f694e5d2
KH
4437
4438 xerrno = errno;
6720a7fb
JB
4439
4440 /* Make C-g and alarm signals set flags again */
4441 clear_waiting_for_input ();
4442
4443 /* If we woke up due to SIGWINCH, actually change size now. */
4444 do_pending_window_change ();
4445
f694e5d2
KH
4446 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4447 /* We waited the full specified time, so return now. */
4448 break;
4449
6720a7fb
JB
4450 if (nfds == -1)
4451 {
4452 /* If the system call was interrupted, then go around the
4453 loop again. */
f694e5d2 4454 if (xerrno == EINTR)
8db121c4 4455 FD_ZERO (&waitchannels);
f694e5d2
KH
4456 else
4457 error ("select error: %s", strerror (xerrno));
6720a7fb
JB
4458 }
4459#ifdef sun
4460 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
4461 /* System sometimes fails to deliver SIGIO. */
4462 kill (getpid (), SIGIO);
4463#endif
7324d660 4464#ifdef SIGIO
f76475ad 4465 if (XINT (read_kbd) && interrupt_input && (waitchannels & 1))
e643c5be 4466 kill (getpid (), SIGIO);
7324d660 4467#endif
6720a7fb 4468
f694e5d2
KH
4469 /* Check for keyboard input */
4470
f854a00b 4471 if ((XINT (read_kbd) != 0)
f694e5d2
KH
4472 && detect_input_pending_run_timers (do_display))
4473 {
4474 swallow_events (do_display);
4475 if (detect_input_pending_run_timers (do_display))
4476 break;
4477 }
0a65b032 4478
f854a00b
RS
4479 /* If wait_for_cell. check for keyboard input
4480 but don't run any timers.
4481 ??? (It seems wrong to me to check for keyboard
4482 input at all when wait_for_cell, but the code
4483 has been this way since July 1994.
4484 Try changing this after version 19.31.) */
4485 if (wait_for_cell
4486 && detect_input_pending ())
4487 {
4488 swallow_events (do_display);
4489 if (detect_input_pending ())
4490 break;
4491 }
4492
0a65b032
RS
4493 /* Exit now if the cell we're waiting for became non-nil. */
4494 if (wait_for_cell && ! NILP (*wait_for_cell))
4495 break;
6720a7fb
JB
4496 }
4497
a87b802f
JB
4498 start_polling ();
4499
6720a7fb
JB
4500 return 0;
4501}
4502
4503
4504DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
51ab806a 4505 /* Don't confuse make-docfile by having two doc strings for this function.
312c9964
RS
4506 make-docfile does not pay attention to #if, for good reason! */
4507 0)
6720a7fb
JB
4508 (name)
4509 register Lisp_Object name;
4510{
4511 return Qnil;
4512}
4513
4514/* Kill all processes associated with `buffer'.
4515 If `buffer' is nil, kill all processes.
4516 Since we have no subprocesses, this does nothing. */
4517
4518kill_buffer_processes (buffer)
4519 Lisp_Object buffer;
4520{
4521}
4522
4523init_process ()
4524{
4525}
4526
4527syms_of_process ()
4528{
4529 defsubr (&Sget_buffer_process);
4530}
4531
4532\f
4533#endif /* not subprocesses */