(READ_CHILD_OUTPUT): Macro deleted.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 86, 87, 88, 93, 94, 95, 1996
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
21
22
23 #include <signal.h>
24
25 #include <config.h>
26
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
35 #ifdef subprocesses
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>
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46
47 #ifdef WINDOWSNT
48 #include <stdlib.h>
49 #include <fcntl.h>
50 #endif /* not WINDOWSNT */
51
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>
57 #ifdef NEED_NET_ERRNO_H
58 #include <net/errno.h>
59 #endif /* NEED_NET_ERRNO_H */
60 #endif /* HAVE_SOCKETS */
61
62 /* TERM is a poor-man's SLIP, used on Linux. */
63 #ifdef TERM
64 #include <client.h>
65 #endif
66
67 /* On some systems, e.g. DGUX, inet_addr returns a 'struct in_addr'. */
68 #ifdef HAVE_BROKEN_INET_ADDR
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
76 #if defined(BSD_SYSTEM) || defined(STRIDE)
77 #include <sys/ioctl.h>
78 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
79 #include <fcntl.h>
80 #endif /* HAVE_PTYS and no O_NDELAY */
81 #endif /* BSD_SYSTEM || STRIDE */
82
83 #ifdef BROKEN_O_NONBLOCK
84 #undef O_NONBLOCK
85 #endif /* BROKEN_O_NONBLOCK */
86
87 #ifdef NEED_BSDTTY
88 #include <bsdtty.h>
89 #endif
90
91 #ifdef IRIS
92 #include <sys/sysmacros.h> /* for "minor" */
93 #endif /* not IRIS */
94
95 #include "systime.h"
96 #include "systty.h"
97
98 #include "lisp.h"
99 #include "window.h"
100 #include "buffer.h"
101 #include "charset.h"
102 #include "coding.h"
103 #include "process.h"
104 #include "termhooks.h"
105 #include "termopts.h"
106 #include "commands.h"
107 #include "frame.h"
108 #include "blockinput.h"
109
110 #define max(a, b) ((a) > (b) ? (a) : (b))
111
112 Lisp_Object Qprocessp;
113 Lisp_Object Qrun, Qstop, Qsignal, Qopen, Qclosed;
114 Lisp_Object Qlast_nonmenu_event;
115 /* Qexit is declared and initialized in eval.c. */
116
117 /* a process object is a network connection when its childp field is neither
118 Qt nor Qnil but is instead a cons cell (HOSTNAME PORTNUM). */
119
120 #ifdef HAVE_SOCKETS
121 #define NETCONN_P(p) (GC_CONSP (XPROCESS (p)->childp))
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
142 #include "syswait.h"
143
144 extern int errno;
145 extern char *strerror ();
146 #ifdef VMS
147 extern char *sys_errlist[];
148 #endif
149
150 #ifndef HAVE_H_ERRNO
151 extern int h_errno;
152 #endif
153
154 #ifndef SYS_SIGLIST_DECLARED
155 #ifndef VMS
156 #ifndef BSD4_1
157 #ifndef WINDOWSNT
158 #ifndef LINUX
159 extern char *sys_siglist[];
160 #endif /* not LINUX */
161 #else /* BSD4_1 */
162 char *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 };
191 #endif /* not WINDOWSNT */
192 #endif
193 #endif /* VMS */
194 #endif /* ! SYS_SIGLIST_DECLARED */
195
196 /* t means use pty, nil means use a pipe,
197 maybe other values to come. */
198 static Lisp_Object Vprocess_connection_type;
199
200 #ifdef SKTPAIR
201 #ifndef HAVE_SOCKETS
202 #include <sys/socket.h>
203 #endif
204 #endif /* SKTPAIR */
205
206 /* These next two vars are non-static since sysdep.c uses them in the
207 emulation of `select'. */
208 /* Number of events of change of status of a process. */
209 int process_tick;
210 /* Number of events for which the user or sentinel has been notified. */
211 int update_tick;
212
213 #include "sysselect.h"
214
215 /* If we support a window system, turn on the code to poll periodically
216 to detect C-g. It isn't actually used when doing interrupt input. */
217 #ifdef HAVE_WINDOW_SYSTEM
218 #define POLL_FOR_INPUT
219 #endif
220
221 /* Mask of bits indicating the descriptors that we wait for input on. */
222
223 static SELECT_TYPE input_wait_mask;
224
225 /* Mask that excludes keyboard input descriptor (s). */
226
227 static SELECT_TYPE non_keyboard_wait_mask;
228
229 /* Mask that excludes process input descriptor (s). */
230
231 static SELECT_TYPE non_process_wait_mask;
232
233 /* The largest descriptor currently in use for a process object. */
234 static int max_process_desc;
235
236 /* The largest descriptor currently in use for keyboard input. */
237 static int max_keyboard_desc;
238
239 /* Nonzero means delete a process right away if it exits. */
240 static int delete_exited_processes;
241
242 /* Indexed by descriptor, gives the process (if any) for that descriptor */
243 Lisp_Object chan_process[MAXDESC];
244
245 /* Alist of elements (NAME . PROCESS) */
246 Lisp_Object Vprocess_alist;
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
254 /* Don't make static; need to access externally. */
255 int proc_buffered_char[MAXDESC];
256
257 /* Table of `struct coding-system' for each process. */
258 static struct coding_system *proc_decode_coding_system[MAXDESC];
259 static struct coding_system *proc_encode_coding_system[MAXDESC];
260
261 static Lisp_Object get_process ();
262
263 extern EMACS_TIME timer_check ();
264 extern int timers_run;
265
266 /* Maximum number of bytes to send to a pty without an eof. */
267 static int pty_max_bytes;
268
269 #ifdef HAVE_PTYS
270 /* The file name of the pty opened by allocate_pty. */
271
272 static char pty_name[24];
273 #endif
274 \f
275 /* Compute the Lisp form of the process status, p->status, from
276 the numeric status that was returned by `wait'. */
277
278 Lisp_Object status_convert ();
279
280 update_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
290 /* Convert a process status word in Unix format to
291 the list that we use internally. */
292
293 Lisp_Object
294 status_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
312 void
313 decode_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
321 if (SYMBOLP (l))
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);
332 tem = XCONS (tem)->cdr;
333 *coredump = !NILP (tem);
334 }
335 }
336
337 /* Return a string describing a process status list. */
338
339 Lisp_Object
340 status_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 {
351 char *signame = 0;
352 if (code < NSIG)
353 {
354 #ifndef VMS
355 /* Cast to suppress warning if the table has const char *. */
356 signame = (char *) sys_siglist[code];
357 #else
358 signame = sys_errlist[code];
359 #endif
360 }
361 if (signame == 0)
362 signame = "unknown";
363 string = build_string (signame);
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");
372 string = Fnumber_to_string (make_number (code));
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
382
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
388 int
389 allocate_pty ()
390 {
391 struct stat stb;
392 register c, i;
393 int fd;
394
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
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
411 #else
412 sprintf (pty_name, "/dev/pty%c%x", c, i);
413 #endif /* no PTY_NAME_SPRINTF */
414
415 #ifdef PTY_OPEN
416 PTY_OPEN;
417 #else /* no PTY_OPEN */
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)
424 return -1;
425 #else /* not IRIS */
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;
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
439 #endif /* not IRIS */
440 #endif /* no PTY_OPEN */
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
448 #else
449 sprintf (pty_name, "/dev/tty%c%x", c, i);
450 #endif /* no PTY_TTY_NAME_SPRINTF */
451 #ifndef UNIPLUS
452 if (access (pty_name, 6) != 0)
453 {
454 close (fd);
455 #if !defined(IRIS) && !defined(__sgi)
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
470 Lisp_Object
471 make_process (name)
472 Lisp_Object name;
473 {
474 struct Lisp_Vector *vec;
475 register Lisp_Object val, tem, name1;
476 register struct Lisp_Process *p;
477 char suffix[10];
478 register int i;
479
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
486 XSETINT (p->infd, -1);
487 XSETINT (p->outfd, -1);
488 XSETFASTINT (p->pid, 0);
489 XSETFASTINT (p->tick, 0);
490 XSETFASTINT (p->update_tick, 0);
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;
508 XSETPROCESS (val, p);
509 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
510 return val;
511 }
512
513 remove_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);
520
521 deactivate_process (proc);
522 }
523 \f
524 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
525 "Return t if OBJECT is a process.")
526 (object)
527 Lisp_Object object;
528 {
529 return PROCESSP (object) ? Qt : Qnil;
530 }
531
532 DEFUN ("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 {
537 if (PROCESSP (name))
538 return name;
539 CHECK_STRING (name, 0);
540 return Fcdr (Fassoc (name, Vprocess_alist));
541 }
542
543 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
544 "Return the (or, a) process associated with BUFFER.\n\
545 BUFFER may be a buffer or the name of one.")
546 (buffer)
547 register Lisp_Object buffer;
548 {
549 register Lisp_Object buf, tail, proc;
550
551 if (NILP (buffer)) return Qnil;
552 buf = Fget_buffer (buffer);
553 if (NILP (buf)) return Qnil;
554
555 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
556 {
557 proc = Fcdr (Fcar (tail));
558 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
559 return proc;
560 }
561 return Qnil;
562 }
563
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. */
568
569 static Lisp_Object
570 get_process (name)
571 register Lisp_Object name;
572 {
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 ();
584 else
585 obj = name;
586
587 /* Now obj should be either a buffer object or a process object.
588 */
589 if (BUFFERP (obj))
590 {
591 proc = Fget_buffer_process (obj);
592 if (NILP (proc))
593 error ("Buffer %s has no process", XSTRING (XBUFFER (obj)->name)->data);
594 }
595 else
596 {
597 CHECK_PROCESS (obj, 0);
598 proc = obj;
599 }
600 return proc;
601 }
602
603 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
604 "Delete PROCESS: kill it and forget about it immediately.\n\
605 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
606 nil, indicating the current buffer's process.")
607 (process)
608 register Lisp_Object process;
609 {
610 process = get_process (process);
611 XPROCESS (process)->raw_status_low = Qnil;
612 XPROCESS (process)->raw_status_high = Qnil;
613 if (NETCONN_P (process))
614 {
615 XPROCESS (process)->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
616 XSETINT (XPROCESS (process)->tick, ++process_tick);
617 }
618 else if (XINT (XPROCESS (process)->infd) >= 0)
619 {
620 Fkill_process (process, Qnil);
621 /* Do this now, since remove_process will make sigchld_handler do nothing. */
622 XPROCESS (process)->status
623 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
624 XSETINT (XPROCESS (process)->tick, ++process_tick);
625 status_notify ();
626 }
627 remove_process (process);
628 return Qnil;
629 }
630 \f
631 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
632 "Return the status of PROCESS: a symbol, one of these:\n\
633 run -- for a process that is running.\n\
634 stop -- for a process stopped but continuable.\n\
635 exit -- for a process that has exited.\n\
636 signal -- for a process that has got a fatal signal.\n\
637 open -- for a network stream connection that is open.\n\
638 closed -- for a network stream connection that is closed.\n\
639 nil -- if arg is a process name and no such process exists.\n\
640 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
641 nil, indicating the current buffer's process.")
642 (process)
643 register Lisp_Object process;
644 {
645 register struct Lisp_Process *p;
646 register Lisp_Object status;
647
648 if (STRINGP (process))
649 process = Fget_process (process);
650 else
651 process = get_process (process);
652
653 if (NILP (process))
654 return process;
655
656 p = XPROCESS (process);
657 if (!NILP (p->raw_status_low))
658 update_status (p);
659 status = p->status;
660 if (CONSP (status))
661 status = XCONS (status)->car;
662 if (NETCONN_P (process))
663 {
664 if (EQ (status, Qrun))
665 status = Qopen;
666 else if (EQ (status, Qexit))
667 status = Qclosed;
668 }
669 return status;
670 }
671
672 DEFUN ("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\
675 If PROCESS has not yet exited or died, return 0.")
676 (process)
677 register Lisp_Object process;
678 {
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;
684 return make_number (0);
685 }
686
687 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
688 "Return the process id of PROCESS.\n\
689 This is the pid of the Unix process which PROCESS uses or talks to.\n\
690 For a network connection, this value is nil.")
691 (process)
692 register Lisp_Object process;
693 {
694 CHECK_PROCESS (process, 0);
695 return XPROCESS (process)->pid;
696 }
697
698 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
699 "Return the name of PROCESS, as a string.\n\
700 This is the name of the program invoked in PROCESS,\n\
701 possibly modified to make it unique among process names.")
702 (process)
703 register Lisp_Object process;
704 {
705 CHECK_PROCESS (process, 0);
706 return XPROCESS (process)->name;
707 }
708
709 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
710 "Return the command that was executed to start PROCESS.\n\
711 This is a list of strings, the first string being the program executed\n\
712 and the rest of the strings being the arguments given to it.\n\
713 For a non-child channel, this is nil.")
714 (process)
715 register Lisp_Object process;
716 {
717 CHECK_PROCESS (process, 0);
718 return XPROCESS (process)->command;
719 }
720
721 DEFUN ("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\
723 This is the terminal that the process itself reads and writes on,\n\
724 not the name of the pty that Emacs uses to talk with that terminal.")
725 (process)
726 register Lisp_Object process;
727 {
728 CHECK_PROCESS (process, 0);
729 return XPROCESS (process)->tty_name;
730 }
731
732 DEFUN ("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).")
735 (process, buffer)
736 register Lisp_Object process, buffer;
737 {
738 CHECK_PROCESS (process, 0);
739 if (!NILP (buffer))
740 CHECK_BUFFER (buffer, 1);
741 XPROCESS (process)->buffer = buffer;
742 return buffer;
743 }
744
745 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
746 1, 1, 0,
747 "Return the buffer PROCESS is associated with.\n\
748 Output from PROCESS is inserted in this buffer\n\
749 unless PROCESS has a filter.")
750 (process)
751 register Lisp_Object process;
752 {
753 CHECK_PROCESS (process, 0);
754 return XPROCESS (process)->buffer;
755 }
756
757 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
758 1, 1, 0,
759 "Return the marker for the end of the last output from PROCESS.")
760 (process)
761 register Lisp_Object process;
762 {
763 CHECK_PROCESS (process, 0);
764 return XPROCESS (process)->mark;
765 }
766
767 DEFUN ("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\
770 t means stop accepting output from the process.\n\
771 When a process has a filter, each time it does output\n\
772 the entire string of output is passed to the filter.\n\
773 The filter gets two arguments: the process and the string of output.\n\
774 If the process has a filter, its buffer is not used for output.")
775 (process, filter)
776 register Lisp_Object process, filter;
777 {
778 CHECK_PROCESS (process, 0);
779 if (EQ (filter, Qt))
780 {
781 FD_CLR (XINT (XPROCESS (process)->infd), &input_wait_mask);
782 FD_CLR (XINT (XPROCESS (process)->infd), &non_keyboard_wait_mask);
783 }
784 else if (EQ (XPROCESS (process)->filter, Qt))
785 {
786 FD_SET (XINT (XPROCESS (process)->infd), &input_wait_mask);
787 FD_SET (XINT (XPROCESS (process)->infd), &non_keyboard_wait_mask);
788 }
789 XPROCESS (process)->filter = filter;
790 return filter;
791 }
792
793 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
794 1, 1, 0,
795 "Returns the filter function of PROCESS; nil if none.\n\
796 See `set-process-filter' for more info on filter functions.")
797 (process)
798 register Lisp_Object process;
799 {
800 CHECK_PROCESS (process, 0);
801 return XPROCESS (process)->filter;
802 }
803
804 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
805 2, 2, 0,
806 "Give PROCESS the sentinel SENTINEL; nil for none.\n\
807 The sentinel is called as a function when the process changes state.\n\
808 It gets two arguments: the process, and a string describing the change.")
809 (process, sentinel)
810 register Lisp_Object process, sentinel;
811 {
812 CHECK_PROCESS (process, 0);
813 XPROCESS (process)->sentinel = sentinel;
814 return sentinel;
815 }
816
817 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
818 1, 1, 0,
819 "Return the sentinel of PROCESS; nil if none.\n\
820 See `set-process-sentinel' for more info on sentinels.")
821 (process)
822 register Lisp_Object process;
823 {
824 CHECK_PROCESS (process, 0);
825 return XPROCESS (process)->sentinel;
826 }
827
828 DEFUN ("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.")
831 (process, height, width)
832 register Lisp_Object process, height, width;
833 {
834 CHECK_PROCESS (process, 0);
835 CHECK_NATNUM (height, 0);
836 CHECK_NATNUM (width, 0);
837 if (set_window_size (XINT (XPROCESS (process)->infd),
838 XINT (height), XINT(width)) <= 0)
839 return Qnil;
840 else
841 return Qt;
842 }
843
844 DEFUN ("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\
847 Optional second argument if non-nil says to require a query.\n\
848 Value is t if a query was formerly required.")
849 (process, value)
850 register Lisp_Object process, value;
851 {
852 Lisp_Object tem;
853
854 CHECK_PROCESS (process, 0);
855 tem = XPROCESS (process)->kill_without_query;
856 XPROCESS (process)->kill_without_query = Fnull (value);
857
858 return Fnull (tem);
859 }
860
861 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
862 1, 1, 0,
863 "Return the contact info of PROCESS; t for a real child.\n\
864 For 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
872 #if 0 /* Turned off because we don't currently record this info
873 in the process. Perhaps add it. */
874 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
875 "Return the connection type of `PROCESS'.\n\
876 The 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
884 \f
885 Lisp_Object
886 list_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
895 XSETFASTINT (minspace, 1);
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 ("\
903 Proc Status Buffer Tty Command\n\
904 ---- ------ ------ --- -------\n", -1);
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;
921 if (CONSP (p->status))
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)
931 write_string (sys_errlist [XINT (tem)], -1);
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 {
954 sprintf (tembuf, " %d", (int) XFASTINT (tem));
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
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
979 if (NETCONN_P (proc))
980 {
981 sprintf (tembuf, "(network stream connection to %s)\n",
982 XSTRING (XCONS (p->childp)->car)->data);
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
1003 DEFUN ("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\
1006 after 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
1014 DEFUN ("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
1021 /* Starting asynchronous inferior processes. */
1022
1023 static Lisp_Object start_process_unwind ();
1024
1025 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1026 "Start a program in a subprocess. Return the process object for it.\n\
1027 Args are NAME BUFFER PROGRAM &rest PROGRAM-ARGS\n\
1028 NAME is name for process. It is modified if necessary to make it unique.\n\
1029 BUFFER 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\
1033 with any buffer.\n\
1034 Third arg is program file name. It is searched for as in the shell.\n\
1035 Remaining arguments are strings to give program as arguments.")
1036 (nargs, args)
1037 int nargs;
1038 register Lisp_Object *args;
1039 {
1040 Lisp_Object buffer, name, program, proc, current_dir, tem;
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;
1048 int count = specpdl_ptr - specpdl;
1049
1050 buffer = args[1];
1051 if (!NILP (buffer))
1052 buffer = Fget_buffer_create (buffer);
1053
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
1070 current_dir
1071 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
1072 Qnil);
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
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 }
1106 /* Need to add code here to check for program existence on VMS */
1107
1108 #else /* not VMS */
1109 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1110
1111 /* If program file name is not absolute, search our path for it */
1112 if (!IS_DIRECTORY_SEP (XSTRING (program)->data[0])
1113 && !(XSTRING (program)->size > 1
1114 && IS_DEVICE_SEP (XSTRING (program)->data[1])))
1115 {
1116 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1117
1118 tem = Qnil;
1119 GCPRO4 (name, program, buffer, current_dir);
1120 openp (Vexec_path, program, EXEC_SUFFIXES, &tem, 1);
1121 UNGCPRO;
1122 if (NILP (tem))
1123 report_file_error ("Searching for program", Fcons (program, Qnil));
1124 tem = Fexpand_file_name (tem, Qnil);
1125 new_argv[0] = XSTRING (tem)->data;
1126 }
1127 else
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 }
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;
1142 #endif /* not VMS */
1143
1144 proc = make_process (name);
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);
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
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
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;
1176
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;
1187 else if (CONSP (Vdefault_process_coding_system))
1188 val = XCONS (Vdefault_process_coding_system)->car;
1189 }
1190 XPROCESS (proc)->decode_coding_system = val;
1191
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;
1205 else if (CONSP (Vdefault_process_coding_system))
1206 val = XCONS (Vdefault_process_coding_system)->cdr;
1207 }
1208 XPROCESS (proc)->encode_coding_system = val;
1209 }
1210
1211 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1212 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1213
1214 create_process (proc, new_argv, current_dir);
1215
1216 return unbind_to (count, proc);
1217 }
1218
1219 /* This function is the unwind_protect form for Fstart_process. If
1220 PROC doesn't have its pid set, then we know someone has signaled
1221 an error and the process wasn't started successfully, so we should
1222 remove it from the process list. */
1223 static Lisp_Object
1224 start_process_unwind (proc)
1225 Lisp_Object proc;
1226 {
1227 if (!PROCESSP (proc))
1228 abort ();
1229
1230 /* Was PROC started successfully? */
1231 if (XINT (XPROCESS (proc)->pid) <= 0)
1232 remove_process (proc);
1233
1234 return Qnil;
1235 }
1236
1237
1238 SIGTYPE
1239 create_process_1 (signo)
1240 int signo;
1241 {
1242 #if defined (USG) && !defined (POSIX_SIGNALS)
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. */
1255 int sigchld_deferred;
1256
1257 SIGTYPE
1258 create_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. */
1269 create_process (process, new_argv, current_dir)
1270 Lisp_Object process;
1271 char **new_argv;
1272 Lisp_Object current_dir;
1273 {
1274 int pid, inchannel, outchannel;
1275 int sv[2];
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 */
1285 #ifdef SIGCHLD
1286 SIGTYPE (*sigchld)();
1287 #endif
1288 #endif /* !POSIX_SIGNALS */
1289 /* Use volatile to protect variables from being clobbered by longjmp. */
1290 volatile int forkin, forkout;
1291 volatile int pty_flag = 0;
1292 extern char **environ;
1293
1294 inchannel = outchannel = -1;
1295
1296 #ifdef HAVE_PTYS
1297 if (!NILP (Vprocess_connection_type))
1298 outchannel = inchannel = allocate_pty ();
1299
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);
1356 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1357 #else
1358 #ifdef O_NDELAY
1359 fcntl (inchannel, F_SETFL, O_NDELAY);
1360 fcntl (outchannel, F_SETFL, O_NDELAY);
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;
1367 XSETINT (XPROCESS (process)->infd, inchannel);
1368 XSETINT (XPROCESS (process)->outfd, outchannel);
1369 /* Record the tty descriptor used in the subprocess. */
1370 if (forkin < 0)
1371 XPROCESS (process)->subtty = Qnil;
1372 else
1373 XSETFASTINT (XPROCESS (process)->subtty, forkin);
1374 XPROCESS (process)->pty_flag = (pty_flag ? Qt : Qnil);
1375 XPROCESS (process)->status = Qrun;
1376 if (!proc_decode_coding_system[inchannel])
1377 proc_decode_coding_system[inchannel]
1378 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
1379 setup_coding_system (XPROCESS (process)->decode_coding_system,
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));
1384 setup_coding_system (XPROCESS (process)->encode_coding_system,
1385 proc_encode_coding_system[outchannel]);
1386
1387 /* Delay interrupts until we have a chance to store
1388 the new fork's pid in its process structure */
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 */
1407 #ifdef SIGCHLD
1408 #ifdef BSD4_1
1409 sighold (SIGCHLD);
1410 #else /* not BSD4_1 */
1411 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
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 */
1421 #endif /* !POSIX_SIGNALS */
1422
1423 FD_SET (inchannel, &input_wait_mask);
1424 FD_SET (inchannel, &non_keyboard_wait_mask);
1425 if (inchannel > max_process_desc)
1426 max_process_desc = inchannel;
1427
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
1436 BLOCK_INPUT;
1437
1438 {
1439 /* child_setup must clobber environ on systems with true vfork.
1440 Protect it from permanent change. */
1441 char **save_environ = environ;
1442
1443 #ifndef WINDOWSNT
1444 pid = vfork ();
1445 if (pid == 0)
1446 #endif /* not WINDOWSNT */
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
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 ();
1464 /* Make the pty's terminal the controlling terminal. */
1465 if (pty_flag)
1466 {
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);
1471 #endif
1472 }
1473 #else /* not HAVE_SETSID */
1474 #ifdef USG
1475 /* It's very important to call setpgrp here and no time
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 */
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
1491 #if defined (NTTYDISC) && defined (TIOCSETD)
1492 if (pty_flag && xforkin >= 0)
1493 {
1494 /* Use new line discipline. */
1495 int ldisc = NTTYDISC;
1496 ioctl (xforkin, TIOCSETD, &ldisc);
1497 }
1498 #endif
1499 #endif
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);
1510 #ifndef USG
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. */
1514 #ifdef HAVE_SETPGID
1515 setpgid (0, 0);
1516 #else
1517 setpgrp (0, 0);
1518 #endif
1519 #endif
1520 }
1521 #endif /* TIOCNOTTY */
1522
1523 #if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
1524 /*** There is a suggestion that this ought to be a
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. */
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 {
1534 #ifdef SET_CHILD_PTY_PGRP
1535 int pgrp = getpid ();
1536 #endif
1537
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
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
1551 #ifdef SET_CHILD_PTY_PGRP
1552 ioctl (xforkin, TIOCSPGRP, &pgrp);
1553 ioctl (xforkout, TIOCSPGRP, &pgrp);
1554 #endif
1555 }
1556 #endif /* not UNIPLUS and not RTU and not DONT_REOPEN_PTY */
1557
1558 #ifdef SETUP_SLAVE_PTY
1559 if (pty_flag)
1560 {
1561 SETUP_SLAVE_PTY;
1562 }
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
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 */
1579 #ifdef SIGCHLD
1580 #ifdef BSD4_1
1581 sigrelse (SIGCHLD);
1582 #else /* not BSD4_1 */
1583 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1584 sigsetmask (SIGEMPTYMASK);
1585 #else /* ordinary USG */
1586 #if 0
1587 signal (SIGCHLD, sigchld);
1588 #endif
1589 #endif /* ordinary USG */
1590 #endif /* not BSD4_1 */
1591 #endif /* SIGCHLD */
1592 #endif /* !POSIX_SIGNALS */
1593
1594 if (pty_flag)
1595 child_setup_tty (xforkout);
1596 #ifdef WINDOWSNT
1597 pid = child_setup (xforkin, xforkout, xforkout,
1598 new_argv, 1, current_dir);
1599 #else /* not WINDOWSNT */
1600 child_setup (xforkin, xforkout, xforkout,
1601 new_argv, 1, current_dir);
1602 #endif /* not WINDOWSNT */
1603 }
1604 environ = save_environ;
1605 }
1606
1607 UNBLOCK_INPUT;
1608
1609 /* This runs in the Emacs process. */
1610 if (pid < 0)
1611 {
1612 if (forkin >= 0)
1613 close (forkin);
1614 if (forkin != forkout && forkout >= 0)
1615 close (forkout);
1616 }
1617 else
1618 {
1619 /* vfork succeeded. */
1620 XSETFASTINT (XPROCESS (process)->pid, pid);
1621
1622 #ifdef WINDOWSNT
1623 register_child (pid, inchannel);
1624 #endif /* WINDOWSNT */
1625
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);
1639
1640 #ifdef HAVE_PTYS
1641 if (pty_flag)
1642 XPROCESS (process)->tty_name = build_string (pty_name);
1643 else
1644 #endif
1645 XPROCESS (process)->tty_name = Qnil;
1646 }
1647
1648 /* Restore the signal state whether vfork succeeded or not.
1649 (We will signal an error, below, if it failed.) */
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 */
1662 #ifdef SIGCHLD
1663 #ifdef BSD4_1
1664 sigrelse (SIGCHLD);
1665 #else /* not BSD4_1 */
1666 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
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 */
1679 #endif /* !POSIX_SIGNALS */
1680
1681 /* Now generate the error if vfork failed. */
1682 if (pid < 0)
1683 report_file_error ("Doing vfork", Qnil);
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
1695 DEFUN ("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\
1698 Returns a subprocess-object to represent the connection.\n\
1699 Input and output work as for subprocesses; `delete-process' closes it.\n\
1700 Args are NAME BUFFER HOST SERVICE.\n\
1701 NAME is name for process. It is modified if necessary to make it unique.\n\
1702 BUFFER 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\
1707 Third arg is name of the host to connect to, or its IP address.\n\
1708 Fourth 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]);
1719 IN_ADDR numeric_addr;
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;
1725 int retry = 0;
1726 int count = specpdl_ptr - specpdl;
1727
1728 #ifdef WINDOWSNT
1729 /* Ensure socket support is loaded if available. */
1730 init_winsock (TRUE);
1731 #endif
1732
1733 GCPRO4 (name, buffer, host, service);
1734 CHECK_STRING (name, 0);
1735 CHECK_STRING (host, 0);
1736 if (INTEGERP (service))
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
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
1754 #ifndef TERM
1755 while (1)
1756 {
1757 #ifdef TRY_AGAIN
1758 h_errno = 0;
1759 #endif
1760 immediate_quit = 1;
1761 QUIT;
1762 host_info_ptr = gethostbyname (XSTRING (host)->data);
1763 immediate_quit = 0;
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 }
1770 if (host_info_ptr == 0)
1771 /* Attempt to interpret host as numeric inet address */
1772 {
1773 numeric_addr = inet_addr ((char *) XSTRING (host)->data);
1774 if (NUMERIC_ADDR_ERROR)
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;
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);
1788 addr_list[1] = 0;
1789 /* numeric_addr isn't null-terminated; it has fixed length. */
1790 host_info.h_length = sizeof (numeric_addr);
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
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
1812 loop:
1813
1814 immediate_quit = 1;
1815 QUIT;
1816
1817 if (connect (s, (struct sockaddr *) &address, sizeof address) == -1
1818 && errno != EISCONN)
1819 {
1820 int xerrno = errno;
1821
1822 immediate_quit = 0;
1823
1824 if (errno == EINTR)
1825 goto loop;
1826 if (errno == EADDRINUSE && retry < 20)
1827 {
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);
1832 retry++;
1833 goto loop;
1834 }
1835
1836 close (s);
1837
1838 if (interrupt_input)
1839 request_sigio ();
1840
1841 errno = xerrno;
1842 report_file_error ("connection failed",
1843 Fcons (host, Fcons (name, Qnil)));
1844 }
1845
1846 immediate_quit = 0;
1847
1848 #ifdef POLL_FOR_INPUT
1849 unbind_to (count, Qnil);
1850 #endif
1851
1852 if (interrupt_input)
1853 request_sigio ();
1854
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 */
1862
1863 inch = s;
1864 outch = s;
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
1880 XPROCESS (proc)->childp = Fcons (host, Fcons (service, Qnil));
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;
1887 XSETINT (XPROCESS (proc)->infd, inch);
1888 XSETINT (XPROCESS (proc)->outfd, outch);
1889 XPROCESS (proc)->status = Qrun;
1890 FD_SET (inch, &input_wait_mask);
1891 FD_SET (inch, &non_keyboard_wait_mask);
1892 if (inch > max_process_desc)
1893 max_process_desc = inch;
1894
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;
1908
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;
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;
1920 }
1921 XPROCESS (proc)->decode_coding_system = val;
1922
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 }
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;
1937 }
1938 XPROCESS (proc)->encode_coding_system = val;
1939 }
1940
1941 if (!proc_decode_coding_system[inch])
1942 proc_decode_coding_system[inch]
1943 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
1944 setup_coding_system (XPROCESS (proc)->decode_coding_system,
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));
1949 setup_coding_system (XPROCESS (proc)->encode_coding_system,
1950 proc_encode_coding_system[outch]);
1951
1952 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1953 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1954
1955 UNGCPRO;
1956 return proc;
1957 }
1958 #endif /* HAVE_SOCKETS */
1959
1960 deactivate_process (proc)
1961 Lisp_Object proc;
1962 {
1963 register int inchannel, outchannel;
1964 register struct Lisp_Process *p = XPROCESS (proc);
1965
1966 inchannel = XINT (p->infd);
1967 outchannel = XINT (p->outfd);
1968
1969 if (inchannel >= 0)
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);
1977 vs = get_vms_process_pointer (p->pid);
1978 if (vs)
1979 give_back_vms_process_stuff (vs);
1980 }
1981 #else
1982 close (inchannel);
1983 if (outchannel >= 0 && outchannel != inchannel)
1984 close (outchannel);
1985 #endif
1986
1987 XSETINT (p->infd, -1);
1988 XSETINT (p->outfd, -1);
1989 chan_process[inchannel] = Qnil;
1990 FD_CLR (inchannel, &input_wait_mask);
1991 FD_CLR (inchannel, &non_keyboard_wait_mask);
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 }
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
2009 close_process_descs ()
2010 {
2011 #ifndef WINDOWSNT
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 {
2019 int in = XINT (XPROCESS (process)->infd);
2020 int out = XINT (XPROCESS (process)->outfd);
2021 if (in >= 0)
2022 close (in);
2023 if (out >= 0 && in != out)
2024 close (out);
2025 }
2026 }
2027 #endif
2028 }
2029 \f
2030 DEFUN ("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\
2033 It is read into the process' buffers or given to their filter functions.\n\
2034 Non-nil arg PROCESS means do not return until some output has been received\n\
2035 from PROCESS.\n\
2036 Non-nil second arg TIMEOUT and third arg TIMEOUT-MSECS are number of\n\
2037 seconds and microseconds to wait; return after that much time whether\n\
2038 or not there is input.\n\
2039 Return non-nil iff we received any output before the timeout expired.")
2040 (process, timeout, timeout_msecs)
2041 register Lisp_Object process, timeout, timeout_msecs;
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);
2050 if (!INTEGERP (timeout))
2051 XSETINT (timeout, 0);
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 }
2069 else
2070 useconds = 0;
2071
2072 if (! NILP (timeout))
2073 {
2074 CHECK_NUMBER (timeout, 1);
2075 seconds = XINT (timeout);
2076 if (seconds < 0 || (seconds == 0 && useconds == 0))
2077 seconds = -1;
2078 }
2079 else
2080 {
2081 if (NILP (process))
2082 seconds = -1;
2083 else
2084 seconds = 0;
2085 }
2086
2087 if (NILP (process))
2088 XSETFASTINT (process, 0);
2089
2090 return
2091 (wait_reading_process_input (seconds, useconds, process, 0)
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
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. */
2104 static int waiting_for_user_input_p;
2105
2106 /* This is here so breakpoints can be put on it. */
2107 static
2108 wait_reading_process_input_1 ()
2109 {
2110 }
2111
2112 /* Read and dispose of subprocess output while waiting for timeout to
2113 elapse and/or keyboard input to be available.
2114
2115 TIME_LIMIT is:
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
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.
2124
2125 READ_KBD is a lisp value:
2126 0 to ignore keyboard input, or
2127 1 to return when input is available, or
2128 -1 meaning caller will actually read the input, so don't throw to
2129 the quit handler, or
2130 a cons cell, meaning wait until its car is non-nil
2131 (and gobble terminal input into the buffer if any arrives), or
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.
2135
2136 DO_DISPLAY != 0 means redisplay should be done to show subprocess
2137 output that arrives.
2138
2139 If READ_KBD is a pointer to a struct Lisp_Process, then the
2140 function returns true iff we received input from that process
2141 before the timeout elapsed.
2142 Otherwise, return true iff we received input from any process. */
2143
2144 wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
2145 int time_limit, microsecs;
2146 Lisp_Object read_kbd;
2147 int do_display;
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;
2155 int wait_channel = -1;
2156 struct Lisp_Process *wait_proc = 0;
2157 int got_some_input = 0;
2158 Lisp_Object *wait_for_cell = 0;
2159
2160 FD_ZERO (&Available);
2161
2162 /* If read_kbd is a process to watch, set wait_proc and wait_channel
2163 accordingly. */
2164 if (PROCESSP (read_kbd))
2165 {
2166 wait_proc = XPROCESS (read_kbd);
2167 wait_channel = XINT (wait_proc->infd);
2168 XSETFASTINT (read_kbd, 0);
2169 }
2170
2171 /* If waiting for non-nil in a cell, record where. */
2172 if (CONSP (read_kbd))
2173 {
2174 wait_for_cell = &XCONS (read_kbd)->car;
2175 XSETFASTINT (read_kbd, 0);
2176 }
2177
2178 waiting_for_user_input_p = XINT (read_kbd);
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 }
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
2196
2197 while (1)
2198 {
2199 int timeout_reduced_for_timers = 0;
2200
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. */
2204 if (XINT (read_kbd) >= 0)
2205 QUIT;
2206
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
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
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)
2238 {
2239 EMACS_TIME timer_delay;
2240 int old_timers_run;
2241
2242 retry:
2243 old_timers_run = timers_run;
2244 timer_delay = timer_check (1);
2245 if (timers_run != old_timers_run && do_display)
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
2253 /* If there is unread keyboard input, also return. */
2254 if (XINT (read_kbd) != 0
2255 && requeued_events_pending_p ())
2256 break;
2257
2258 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
2259 {
2260 EMACS_TIME difference;
2261 EMACS_SUB_TIME (difference, timer_delay, timeout);
2262 if (EMACS_TIME_NEG_P (difference))
2263 {
2264 timeout = timer_delay;
2265 timeout_reduced_for_timers = 1;
2266 }
2267 }
2268 /* If time_limit is -1, we are not going to wait at all. */
2269 else if (time_limit != -1)
2270 {
2271 /* This is so a breakpoint can be put here. */
2272 wait_reading_process_input_1 ();
2273 }
2274 }
2275
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
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);
2293 if ((select (max (max_process_desc, max_keyboard_desc) + 1,
2294 &Atemp, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
2295 &timeout)
2296 <= 0))
2297 {
2298 /* It's okay for us to do this and then continue with
2299 the loop, since timeout has already been zeroed out. */
2300 clear_waiting_for_input ();
2301 status_notify ();
2302 }
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))
2310 {
2311 int nread, total_nread;
2312
2313 clear_waiting_for_input ();
2314 XSETPROCESS (proc, wait_proc);
2315
2316 /* Read data from the process, until we exhaust it. */
2317 while (XINT (wait_proc->infd) >= 0
2318 && (nread
2319 = read_process_output (proc, XINT (wait_proc->infd))))
2320 total_nread += nread;
2321 if (total_nread > 0 && do_display)
2322 redisplay_preserve_echo_area ();
2323
2324 break;
2325 }
2326
2327 /* Wait till there is something to do */
2328
2329 if (wait_for_cell)
2330 Available = non_process_wait_mask;
2331 else if (! XINT (read_kbd))
2332 Available = non_keyboard_wait_mask;
2333 else
2334 Available = input_wait_mask;
2335
2336 /* If frame size has changed or the window is newly mapped,
2337 redisplay now, before we start to wait. There is a race
2338 condition here; if a SIGIO arrives between now and the select
2339 and indicates that a frame is trashed, the select may block
2340 displaying a trashed screen. */
2341 if (frame_garbaged && do_display)
2342 {
2343 clear_waiting_for_input ();
2344 redisplay_preserve_echo_area ();
2345 if (XINT (read_kbd) < 0)
2346 set_waiting_for_input (&timeout);
2347 }
2348
2349 if (XINT (read_kbd) && detect_input_pending ())
2350 {
2351 nfds = 0;
2352 FD_ZERO (&Available);
2353 }
2354 else
2355 nfds = select (max (max_process_desc, max_keyboard_desc) + 1,
2356 &Available, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
2357 &timeout);
2358
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
2367 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
2368 /* We wanted the full specified time, so return now. */
2369 break;
2370 if (nfds < 0)
2371 {
2372 if (xerrno == EINTR)
2373 FD_ZERO (&Available);
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 */
2380 else if (xerrno == ENOMEM)
2381 FD_ZERO (&Available);
2382 #endif
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
2397 in m/ibmrt-aix.h), and here we just ignore the select error.
2398 Cleanup occurs c/o status_notify after SIGCLD. */
2399 FD_ZERO (&Available); /* Cannot depend on values returned */
2400 #else
2401 abort ();
2402 #endif
2403 }
2404 else
2405 error ("select error: %s", strerror (xerrno));
2406 }
2407 #if defined(sun) && !defined(USG5_4)
2408 else if (nfds > 0 && keyboard_bit_set (&Available)
2409 && interrupt_input)
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." */
2417 kill (getpid (), SIGIO);
2418 #endif
2419
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
2435 /* Check for keyboard input */
2436 /* If there is any, return immediately
2437 to give it higher priority than subprocesses */
2438
2439 if ((XINT (read_kbd) != 0)
2440 && detect_input_pending_run_timers (do_display))
2441 {
2442 swallow_events (do_display);
2443 if (detect_input_pending_run_timers (do_display))
2444 break;
2445 }
2446
2447 /* If there is unread keyboard input, also return. */
2448 if (XINT (read_kbd) != 0
2449 && requeued_events_pending_p ())
2450 break;
2451
2452 /* If wait_for_cell. check for keyboard input
2453 but don't run any timers.
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. */
2457 if (wait_for_cell
2458 && detect_input_pending ())
2459 {
2460 swallow_events (do_display);
2461 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
2462 if (detect_input_pending ())
2463 break;
2464 #endif
2465 }
2466
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
2471 #ifdef SIGIO
2472 /* If we think we have keyboard input waiting, but didn't get SIGIO,
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
2477 if (XINT (read_kbd) && interrupt_input
2478 && keyboard_bit_set (&Available))
2479 kill (getpid (), SIGIO);
2480 #endif
2481
2482 if (! wait_proc)
2483 got_some_input |= nfds > 0;
2484
2485 /* If checking input just got us a size-change event from X,
2486 obey it now if we should. */
2487 if (XINT (read_kbd) || wait_for_cell)
2488 do_pending_window_change ();
2489
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. */
2493 for (channel = 0; channel <= max_process_desc; channel++)
2494 {
2495 if (FD_ISSET (channel, &Available)
2496 && FD_ISSET (channel, &non_keyboard_wait_mask))
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 {
2505 wait_channel = -1;
2506 time_limit = -1;
2507 got_some_input = 1;
2508 }
2509 proc = chan_process[channel];
2510 if (NILP (proc))
2511 continue;
2512
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 ;
2531 #endif
2532 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
2533 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
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 ;
2547 #endif /* O_NDELAY */
2548 #endif /* O_NONBLOCK */
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 ;
2559 #endif /* HAVE_PTYS */
2560 /* If we can detect process termination, don't consider the process
2561 gone just because its pipe is closed. */
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 }
2578 } /* end for each file descriptor */
2579 } /* end while exit conditions not met */
2580
2581 waiting_for_user_input_p = 0;
2582
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. */
2586 if (XINT (read_kbd) >= 0)
2587 {
2588 /* Prevent input_pending from remaining set if we quit. */
2589 clear_input_pending ();
2590 QUIT;
2591 }
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 */
2598 start_polling ();
2599 #endif
2600
2601 return got_some_input;
2602 }
2603 \f
2604 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
2605
2606 static Lisp_Object
2607 read_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
2613 static Lisp_Object
2614 read_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 ();
2620 Fsleep_for (make_number (2), Qnil);
2621 }
2622
2623 /* Read pending output from the process channel,
2624 starting with our buffered-ahead character if we have one.
2625 Yield number of decoded characters read.
2626
2627 This function reads at most 1024 characters.
2628 If you want to read all available subprocess output,
2629 you must call it repeatedly until it returns zero.
2630
2631 The characters read are decoded according to PROC's coding-system
2632 for decoding. */
2633
2634 read_process_output (proc, channel)
2635 Lisp_Object proc;
2636 register int channel;
2637 {
2638 register int nchars;
2639 char *chars;
2640 #ifdef VMS
2641 int chars_allocated = 0; /* If 1, `chars' should be freed later. */
2642 #else
2643 char buf[1024];
2644 #endif
2645 register Lisp_Object outstream;
2646 register struct buffer *old = current_buffer;
2647 register struct Lisp_Process *p = XPROCESS (proc);
2648 register int opoint;
2649 struct coding_system *coding = proc_decode_coding_system[channel];
2650 int chars_in_decoding_buf = 0; /* If 1, `chars' points
2651 XSTRING (p->decoding_buf)->data. */
2652
2653 #ifdef VMS
2654 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
2655
2656 vs = get_vms_process_pointer (p->pid);
2657 if (vs)
2658 {
2659 if (!vs->iosb[0])
2660 return(0); /* Really weird if it does this */
2661 if (!(vs->iosb[0] & 1))
2662 return -1; /* I/O error */
2663 }
2664 else
2665 error ("Could not get VMS process pointer");
2666 chars = vs->inputBuffer;
2667 nchars = clean_vms_buffer (chars, vs->iosb[1]);
2668 if (nchars <= 0)
2669 {
2670 start_vms_process_read (vs); /* Crank up the next read on the process */
2671 return 1; /* Nothing worth printing, say we got 1 */
2672 }
2673 if (coding->carryover_size)
2674 {
2675 /* The data carried over in the previous decoding should be
2676 prepended to the new data read to decode all together. */
2677 char *buf = (char *) xmalloc (nchars + coding->carryover_size);
2678
2679 bcopy (coding->carryover, buf, coding->carryover_size);
2680 bcopy (chars, buf + coding->carryover_size, nchars);
2681 chars = buf;
2682 chars_allocated = 1;
2683 }
2684 #else /* not VMS */
2685
2686 if (coding->carryover_size)
2687 /* The data carried over in the previous decoding should be
2688 prepended to the new data read to decode all together. */
2689 bcopy (coding->carryover, buf, coding->carryover_size);
2690
2691 if (proc_buffered_char[channel] < 0)
2692 nchars = read (channel, buf + coding->carryover_size,
2693 (sizeof buf) - coding->carryover_size);
2694 else
2695 {
2696 buf[coding->carryover_size] = proc_buffered_char[channel];
2697 proc_buffered_char[channel] = -1;
2698 nchars = read (channel, buf + coding->carryover_size + 1,
2699 (sizeof buf) - coding->carryover_size - 1);
2700 if (nchars < 0)
2701 nchars = 1;
2702 else
2703 nchars = nchars + 1;
2704 }
2705 chars = buf;
2706 #endif /* not VMS */
2707
2708 /* At this point, NCHARS holds number of characters just received
2709 (including the one in proc_buffered_char[channel]). */
2710 if (nchars <= 0) return nchars;
2711
2712 /* Now set NCHARS how many bytes we must decode. */
2713 nchars += coding->carryover_size;
2714
2715 if (CODING_REQUIRE_CONVERSION (coding))
2716 {
2717 int require = decoding_buffer_size (coding, nchars);
2718 int consumed, produced;
2719
2720 if (XSTRING (p->decoding_buf)->size < require)
2721 p->decoding_buf = make_uninit_string (require);
2722 produced = decode_coding (coding, chars, XSTRING (p->decoding_buf)->data,
2723 nchars, XSTRING (p->decoding_buf)->size,
2724 &consumed);
2725
2726 /* New coding-system might be found by `decode_coding'. */
2727 if (!EQ (p->decode_coding_system, coding->symbol))
2728 {
2729 p->decode_coding_system = coding->symbol;
2730 setup_coding_system (coding->symbol,
2731 proc_decode_coding_system[channel]);
2732 /* If coding-system for encoding is not yet decided, we set it
2733 as the same as coding-system for decoding. */
2734 if (NILP (p->encode_coding_system))
2735 {
2736 p->encode_coding_system = coding->symbol;
2737 setup_coding_system (coding->symbol,
2738 proc_encode_coding_system[channel]);
2739 }
2740 }
2741 #ifdef VMS
2742 /* Now we don't need the contents of `chars'. */
2743 if (chars_allocated)
2744 free (chars);
2745 #endif
2746 if (produced == 0)
2747 return 0;
2748 chars = XSTRING (p->decoding_buf)->data;
2749 nchars = produced;
2750 chars_in_decoding_buf = 1;
2751 }
2752 #ifdef VMS
2753 else if (chars_allocated)
2754 {
2755 /* Although we don't have to decode the received data, we must
2756 move it to an area which we don't have to free. */
2757 if (! STRINGP (p->decoding_buf)
2758 || XSTRING (p->decoding_buf)->size < nchars)
2759 p->decoding_buf = make_uninit_string (nchars);
2760 bcopy (chars, XSTRING (p->decoding_buf)->data, nchars);
2761 free (chars);
2762 chars = XSTRING (p->decoding_buf)->data;
2763 chars_in_decoding_buf = 1;
2764 }
2765 #endif
2766
2767 outstream = p->filter;
2768 if (!NILP (outstream))
2769 {
2770 /* We inhibit quit here instead of just catching it so that
2771 hitting ^G when a filter happens to be running won't screw
2772 it up. */
2773 int count = specpdl_ptr - specpdl;
2774 Lisp_Object odeactivate;
2775 Lisp_Object obuffer, okeymap;
2776 int outer_running_asynch_code = running_asynch_code;
2777
2778 /* No need to gcpro these, because all we do with them later
2779 is test them for EQness, and none of them should be a string. */
2780 odeactivate = Vdeactivate_mark;
2781 XSETBUFFER (obuffer, current_buffer);
2782 okeymap = current_buffer->keymap;
2783
2784 specbind (Qinhibit_quit, Qt);
2785 specbind (Qlast_nonmenu_event, Qt);
2786
2787 /* In case we get recursively called,
2788 and we already saved the match data nonrecursively,
2789 save the same match data in safely recursive fashion. */
2790 if (outer_running_asynch_code)
2791 {
2792 Lisp_Object tem;
2793 /* Don't clobber the CURRENT match data, either! */
2794 tem = Fmatch_data (Qnil, Qnil);
2795 restore_match_data ();
2796 record_unwind_protect (Fstore_match_data, Fmatch_data (Qnil, Qnil));
2797 Fstore_match_data (tem);
2798 }
2799
2800 /* For speed, if a search happens within this code,
2801 save the match data in a special nonrecursive fashion. */
2802 running_asynch_code = 1;
2803
2804 /* Read and dispose of the process output. */
2805 internal_condition_case_1 (read_process_output_call,
2806 Fcons (outstream,
2807 Fcons (proc,
2808 Fcons (make_string (chars,
2809 nchars),
2810 Qnil))),
2811 !NILP (Vdebug_on_error) ? Qnil : Qerror,
2812 read_process_output_error_handler);
2813
2814 /* If we saved the match data nonrecursively, restore it now. */
2815 restore_match_data ();
2816 running_asynch_code = outer_running_asynch_code;
2817
2818 /* Handling the process output should not deactivate the mark. */
2819 Vdeactivate_mark = odeactivate;
2820
2821 #if 0 /* Call record_asynch_buffer_change unconditionally,
2822 because we might have changed minor modes or other things
2823 that affect key bindings. */
2824 if (! EQ (Fcurrent_buffer (), obuffer)
2825 || ! EQ (current_buffer->keymap, okeymap))
2826 #endif
2827 /* But do it only if the caller is actually going to read events.
2828 Otherwise there's no need to make him wake up, and it could
2829 cause trouble (for example it would make Fsit_for return). */
2830 if (waiting_for_user_input_p == -1)
2831 record_asynch_buffer_change ();
2832
2833 #ifdef VMS
2834 start_vms_process_read (vs);
2835 #endif
2836 unbind_to (count, Qnil);
2837 return nchars;
2838 }
2839
2840 /* If no filter, write into buffer if it isn't dead. */
2841 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
2842 {
2843 Lisp_Object old_read_only;
2844 int old_begv, old_zv;
2845 Lisp_Object odeactivate;
2846 int before;
2847
2848 odeactivate = Vdeactivate_mark;
2849
2850 Fset_buffer (p->buffer);
2851 opoint = PT;
2852 old_read_only = current_buffer->read_only;
2853 old_begv = BEGV;
2854 old_zv = ZV;
2855
2856 current_buffer->read_only = Qnil;
2857
2858 /* Insert new output into buffer
2859 at the current end-of-output marker,
2860 thus preserving logical ordering of input and output. */
2861 if (XMARKER (p->mark)->buffer)
2862 SET_PT (clip_to_bounds (BEGV, marker_position (p->mark), ZV));
2863 else
2864 SET_PT (ZV);
2865 before = PT;
2866
2867 /* If the output marker is outside of the visible region, save
2868 the restriction and widen. */
2869 if (! (BEGV <= PT && PT <= ZV))
2870 Fwiden ();
2871
2872 /* Insert before markers in case we are inserting where
2873 the buffer's mark is, and the user's next command is Meta-y. */
2874 if (chars_in_decoding_buf)
2875 insert_from_string_before_markers (p->decoding_buf, 0, nchars, 0);
2876 else
2877 insert_before_markers (chars, nchars);
2878 Fset_marker (p->mark, make_number (PT), p->buffer);
2879
2880 update_mode_lines++;
2881
2882 /* Make sure opoint and the old restrictions
2883 float ahead of any new text just as point would. */
2884 if (opoint >= before)
2885 opoint += PT - before;
2886 if (old_begv > before)
2887 old_begv += PT - before;
2888 if (old_zv >= before)
2889 old_zv += PT - before;
2890
2891 /* If the restriction isn't what it should be, set it. */
2892 if (old_begv != BEGV || old_zv != ZV)
2893 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
2894
2895 /* Handling the process output should not deactivate the mark. */
2896 Vdeactivate_mark = odeactivate;
2897
2898 current_buffer->read_only = old_read_only;
2899 SET_PT (opoint);
2900 set_buffer_internal (old);
2901 }
2902 #ifdef VMS
2903 start_vms_process_read (vs);
2904 #endif
2905 return nchars;
2906 }
2907
2908 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
2909 0, 0, 0,
2910 "Returns non-nil if emacs is waiting for input from the user.\n\
2911 This is intended for use by asynchronous process output filters and sentinels.")
2912 ()
2913 {
2914 return (waiting_for_user_input_p ? Qt : Qnil);
2915 }
2916 \f
2917 /* Sending data to subprocess */
2918
2919 jmp_buf send_process_frame;
2920
2921 SIGTYPE
2922 send_process_trap ()
2923 {
2924 #ifdef BSD4_1
2925 sigrelse (SIGPIPE);
2926 sigrelse (SIGALRM);
2927 #endif /* BSD4_1 */
2928 longjmp (send_process_frame, 1);
2929 }
2930
2931 /* Send some data to process PROC.
2932 BUF is the beginning of the data; LEN is the number of characters.
2933 OBJECT is the Lisp object that the data comes from.
2934
2935 The data is encoded by PROC's coding-system for encoding before it
2936 is sent. But if the data ends at the middle of multi-byte
2937 representation, that incomplete sequence of bytes are sent without
2938 being encoded. Should we store them in a buffer to prepend them to
2939 the data send later? */
2940
2941 send_process (proc, buf, len, object)
2942 volatile Lisp_Object proc;
2943 char *buf;
2944 int len;
2945 Lisp_Object object;
2946 {
2947 /* Use volatile to protect variables from being clobbered by longjmp. */
2948 int rv;
2949 volatile unsigned char *procname = XSTRING (XPROCESS (proc)->name)->data;
2950 struct coding_system *coding;
2951 struct gcpro gcpro1;
2952
2953 GCPRO1 (object);
2954
2955 #ifdef VMS
2956 struct Lisp_Process *p = XPROCESS (proc);
2957 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
2958 #endif /* VMS */
2959
2960 if (! NILP (XPROCESS (proc)->raw_status_low))
2961 update_status (XPROCESS (proc));
2962 if (! EQ (XPROCESS (proc)->status, Qrun))
2963 error ("Process %s not running", procname);
2964 if (XINT (XPROCESS (proc)->outfd) < 0)
2965 error ("Output file descriptor of %s is closed", procname);
2966
2967 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
2968 if (CODING_REQUIRE_CONVERSION (coding))
2969 {
2970 int require = encoding_buffer_size (coding, len);
2971 int offset, dummy;
2972 char *temp_buf = NULL;
2973
2974 /* Remember the offset of data because a string or a buffer may
2975 be relocated. Setting OFFSET to -1 means we don't have to
2976 care relocation. */
2977 offset = (BUFFERP (object)
2978 ? BUF_PTR_CHAR_POS (XBUFFER (object), (unsigned char *) buf)
2979 : (STRINGP (object)
2980 ? offset = buf - (char *) XSTRING (object)->data
2981 : -1));
2982
2983 if (coding->carryover_size > 0)
2984 {
2985 temp_buf = (char *) xmalloc (len + coding->carryover_size);
2986
2987 if (offset >= 0)
2988 {
2989 if (BUFFERP (object))
2990 buf = (char *) BUF_CHAR_ADDRESS (XBUFFER (object), offset);
2991 else if (STRINGP (object))
2992 buf = offset + (char *) XSTRING (object)->data;
2993 /* Now we don't have to care relocation. */
2994 offset = -1;
2995 }
2996 bcopy (coding->carryover, temp_buf, coding->carryover_size);
2997 bcopy (buf, temp_buf + coding->carryover_size, len);
2998 buf = temp_buf;
2999 }
3000
3001 if (XSTRING (XPROCESS (proc)->encoding_buf)->size < require)
3002 {
3003 XPROCESS (proc)->encoding_buf = make_uninit_string (require);
3004
3005 if (offset >= 0)
3006 {
3007 if (BUFFERP (object))
3008 buf = (char *) BUF_CHAR_ADDRESS (XBUFFER (object), offset);
3009 else if (STRINGP (object))
3010 buf = offset + (char *) XSTRING (object)->data;
3011 }
3012 }
3013 object = XPROCESS (proc)->encoding_buf;
3014 len = encode_coding (coding, buf, XSTRING (object)->data,
3015 len, XSTRING (object)->size, &dummy);
3016 buf = XSTRING (object)->data;
3017 if (temp_buf)
3018 xfree (temp_buf);
3019 }
3020
3021 #ifdef VMS
3022 vs = get_vms_process_pointer (p->pid);
3023 if (vs == 0)
3024 error ("Could not find this process: %x", p->pid);
3025 else if (write_to_vms_process (vs, buf, len))
3026 ;
3027 #else
3028
3029 if (pty_max_bytes == 0)
3030 {
3031 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
3032 pty_max_bytes = fpathconf (XFASTINT (XPROCESS (proc)->outfd),
3033 _PC_MAX_CANON);
3034 if (pty_max_bytes < 0)
3035 pty_max_bytes = 250;
3036 #else
3037 pty_max_bytes = 250;
3038 #endif
3039 /* Deduct one, to leave space for the eof. */
3040 pty_max_bytes--;
3041 }
3042
3043 if (!setjmp (send_process_frame))
3044 while (len > 0)
3045 {
3046 int this = len;
3047 SIGTYPE (*old_sigpipe)();
3048 int flush_pty = 0;
3049
3050 /* Decide how much data we can send in one batch.
3051 Long lines need to be split into multiple batches. */
3052 if (!NILP (XPROCESS (proc)->pty_flag))
3053 {
3054 /* Starting this at zero is always correct when not the first iteration
3055 because the previous iteration ended by sending C-d.
3056 It may not be correct for the first iteration
3057 if a partial line was sent in a separate send_process call.
3058 If that proves worth handling, we need to save linepos
3059 in the process object. */
3060 int linepos = 0;
3061 char *ptr = buf;
3062 char *end = buf + len;
3063
3064 /* Scan through this text for a line that is too long. */
3065 while (ptr != end && linepos < pty_max_bytes)
3066 {
3067 if (*ptr == '\n')
3068 linepos = 0;
3069 else
3070 linepos++;
3071 ptr++;
3072 }
3073 /* If we found one, break the line there
3074 and put in a C-d to force the buffer through. */
3075 this = ptr - buf;
3076 }
3077
3078 /* Send this batch, using one or more write calls. */
3079 while (this > 0)
3080 {
3081 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
3082 rv = write (XINT (XPROCESS (proc)->outfd), buf, this);
3083 signal (SIGPIPE, old_sigpipe);
3084
3085 if (rv < 0)
3086 {
3087 if (0
3088 #ifdef EWOULDBLOCK
3089 || errno == EWOULDBLOCK
3090 #endif
3091 #ifdef EAGAIN
3092 || errno == EAGAIN
3093 #endif
3094 )
3095 /* Buffer is full. Wait, accepting input;
3096 that may allow the program
3097 to finish doing output and read more. */
3098 {
3099 Lisp_Object zero;
3100 int offset;
3101
3102 /* Running filters might relocate buffers or strings.
3103 Arrange to relocate BUF. */
3104 if (BUFFERP (object))
3105 offset = BUF_PTR_CHAR_POS (XBUFFER (object),
3106 (unsigned char *) buf);
3107 else if (STRINGP (object))
3108 offset = buf - (char *) XSTRING (object)->data;
3109
3110 XSETFASTINT (zero, 0);
3111 #ifdef EMACS_HAS_USECS
3112 wait_reading_process_input (0, 20000, zero, 0);
3113 #else
3114 wait_reading_process_input (1, 0, zero, 0);
3115 #endif
3116
3117 if (BUFFERP (object))
3118 buf = (char *) BUF_CHAR_ADDRESS (XBUFFER (object), offset);
3119 else if (STRINGP (object))
3120 buf = offset + (char *) XSTRING (object)->data;
3121
3122 rv = 0;
3123 }
3124 else
3125 /* This is a real error. */
3126 report_file_error ("writing to process", Fcons (proc, Qnil));
3127 }
3128 buf += rv;
3129 len -= rv;
3130 this -= rv;
3131 }
3132
3133 /* If we sent just part of the string, put in an EOF
3134 to force it through, before we send the rest. */
3135 if (len > 0)
3136 Fprocess_send_eof (proc);
3137 }
3138 #endif
3139 else
3140 {
3141 XPROCESS (proc)->raw_status_low = Qnil;
3142 XPROCESS (proc)->raw_status_high = Qnil;
3143 XPROCESS (proc)->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
3144 XSETINT (XPROCESS (proc)->tick, ++process_tick);
3145 deactivate_process (proc);
3146 #ifdef VMS
3147 error ("Error writing to process %s; closed it", procname);
3148 #else
3149 error ("SIGPIPE raised on process %s; closed it", procname);
3150 #endif
3151 }
3152
3153 UNGCPRO;
3154 }
3155
3156 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
3157 3, 3, 0,
3158 "Send current contents of region as input to PROCESS.\n\
3159 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
3160 nil, indicating the current buffer's process.\n\
3161 Called from program, takes three arguments, PROCESS, START and END.\n\
3162 If the region is more than 500 characters long,\n\
3163 it is sent in several bunches. This may happen even for shorter regions.\n\
3164 Output from processes can arrive in between bunches.")
3165 (process, start, end)
3166 Lisp_Object process, start, end;
3167 {
3168 Lisp_Object proc;
3169 int start1;
3170
3171 proc = get_process (process);
3172 validate_region (&start, &end);
3173
3174 if (XINT (start) < GPT && XINT (end) > GPT)
3175 move_gap (start);
3176
3177 start1 = XINT (start);
3178 send_process (proc, POS_ADDR (start1), XINT (end) - XINT (start),
3179 Fcurrent_buffer ());
3180
3181 return Qnil;
3182 }
3183
3184 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
3185 2, 2, 0,
3186 "Send PROCESS the contents of STRING as input.\n\
3187 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
3188 nil, indicating the current buffer's process.\n\
3189 If STRING is more than 500 characters long,\n\
3190 it is sent in several bunches. This may happen even for shorter strings.\n\
3191 Output from processes can arrive in between bunches.")
3192 (process, string)
3193 Lisp_Object process, string;
3194 {
3195 Lisp_Object proc;
3196 CHECK_STRING (string, 1);
3197 proc = get_process (process);
3198 send_process (proc, XSTRING (string)->data, XSTRING (string)->size, string);
3199 return Qnil;
3200 }
3201 \f
3202 /* send a signal number SIGNO to PROCESS.
3203 CURRENT_GROUP means send to the process group that currently owns
3204 the terminal being used to communicate with PROCESS.
3205 This is used for various commands in shell mode.
3206 If NOMSG is zero, insert signal-announcements into process's buffers
3207 right away.
3208
3209 If we can, we try to signal PROCESS by sending control characters
3210 down the pty. This allows us to signal inferiors who have changed
3211 their uid, for which killpg would return an EPERM error. */
3212
3213 static void
3214 process_send_signal (process, signo, current_group, nomsg)
3215 Lisp_Object process;
3216 int signo;
3217 Lisp_Object current_group;
3218 int nomsg;
3219 {
3220 Lisp_Object proc;
3221 register struct Lisp_Process *p;
3222 int gid;
3223 int no_pgrp = 0;
3224
3225 proc = get_process (process);
3226 p = XPROCESS (proc);
3227
3228 if (!EQ (p->childp, Qt))
3229 error ("Process %s is not a subprocess",
3230 XSTRING (p->name)->data);
3231 if (XINT (p->infd) < 0)
3232 error ("Process %s is not active",
3233 XSTRING (p->name)->data);
3234
3235 if (NILP (p->pty_flag))
3236 current_group = Qnil;
3237
3238 /* If we are using pgrps, get a pgrp number and make it negative. */
3239 if (!NILP (current_group))
3240 {
3241 #ifdef SIGNALS_VIA_CHARACTERS
3242 /* If possible, send signals to the entire pgrp
3243 by sending an input character to it. */
3244
3245 /* TERMIOS is the latest and bestest, and seems most likely to
3246 work. If the system has it, use it. */
3247 #ifdef HAVE_TERMIOS
3248 struct termios t;
3249
3250 switch (signo)
3251 {
3252 case SIGINT:
3253 tcgetattr (XINT (p->infd), &t);
3254 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
3255 return;
3256
3257 case SIGQUIT:
3258 tcgetattr (XINT (p->infd), &t);
3259 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
3260 return;
3261
3262 case SIGTSTP:
3263 tcgetattr (XINT (p->infd), &t);
3264 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
3265 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
3266 #else
3267 send_process (proc, &t.c_cc[VSUSP], 1, Qnil);
3268 #endif
3269 return;
3270 }
3271
3272 #else /* ! HAVE_TERMIOS */
3273
3274 /* On Berkeley descendants, the following IOCTL's retrieve the
3275 current control characters. */
3276 #if defined (TIOCGLTC) && defined (TIOCGETC)
3277
3278 struct tchars c;
3279 struct ltchars lc;
3280
3281 switch (signo)
3282 {
3283 case SIGINT:
3284 ioctl (XINT (p->infd), TIOCGETC, &c);
3285 send_process (proc, &c.t_intrc, 1, Qnil);
3286 return;
3287 case SIGQUIT:
3288 ioctl (XINT (p->infd), TIOCGETC, &c);
3289 send_process (proc, &c.t_quitc, 1, Qnil);
3290 return;
3291 #ifdef SIGTSTP
3292 case SIGTSTP:
3293 ioctl (XINT (p->infd), TIOCGLTC, &lc);
3294 send_process (proc, &lc.t_suspc, 1, Qnil);
3295 return;
3296 #endif /* ! defined (SIGTSTP) */
3297 }
3298
3299 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
3300
3301 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
3302 characters. */
3303 #ifdef TCGETA
3304 struct termio t;
3305 switch (signo)
3306 {
3307 case SIGINT:
3308 ioctl (XINT (p->infd), TCGETA, &t);
3309 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
3310 return;
3311 case SIGQUIT:
3312 ioctl (XINT (p->infd), TCGETA, &t);
3313 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
3314 return;
3315 #ifdef SIGTSTP
3316 case SIGTSTP:
3317 ioctl (XINT (p->infd), TCGETA, &t);
3318 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
3319 return;
3320 #endif /* ! defined (SIGTSTP) */
3321 }
3322 #else /* ! defined (TCGETA) */
3323 Your configuration files are messed up.
3324 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
3325 you'd better be using one of the alternatives above! */
3326 #endif /* ! defined (TCGETA) */
3327 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
3328 #endif /* ! defined HAVE_TERMIOS */
3329 #endif /* ! defined (SIGNALS_VIA_CHARACTERS) */
3330
3331 #ifdef TIOCGPGRP
3332 /* Get the pgrp using the tty itself, if we have that.
3333 Otherwise, use the pty to get the pgrp.
3334 On pfa systems, saka@pfu.fujitsu.co.JP writes:
3335 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
3336 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
3337 His patch indicates that if TIOCGPGRP returns an error, then
3338 we should just assume that p->pid is also the process group id. */
3339 {
3340 int err;
3341
3342 if (!NILP (p->subtty))
3343 err = ioctl (XFASTINT (p->subtty), TIOCGPGRP, &gid);
3344 else
3345 err = ioctl (XINT (p->infd), TIOCGPGRP, &gid);
3346
3347 #ifdef pfa
3348 if (err == -1)
3349 gid = - XFASTINT (p->pid);
3350 #endif /* ! defined (pfa) */
3351 }
3352 if (gid == -1)
3353 no_pgrp = 1;
3354 else
3355 gid = - gid;
3356 #else /* ! defined (TIOCGPGRP ) */
3357 /* Can't select pgrps on this system, so we know that
3358 the child itself heads the pgrp. */
3359 gid = - XFASTINT (p->pid);
3360 #endif /* ! defined (TIOCGPGRP ) */
3361 }
3362 else
3363 gid = - XFASTINT (p->pid);
3364
3365 switch (signo)
3366 {
3367 #ifdef SIGCONT
3368 case SIGCONT:
3369 p->raw_status_low = Qnil;
3370 p->raw_status_high = Qnil;
3371 p->status = Qrun;
3372 XSETINT (p->tick, ++process_tick);
3373 if (!nomsg)
3374 status_notify ();
3375 break;
3376 #endif /* ! defined (SIGCONT) */
3377 case SIGINT:
3378 #ifdef VMS
3379 send_process (proc, "\003", 1, Qnil); /* ^C */
3380 goto whoosh;
3381 #endif
3382 case SIGQUIT:
3383 #ifdef VMS
3384 send_process (proc, "\031", 1, Qnil); /* ^Y */
3385 goto whoosh;
3386 #endif
3387 case SIGKILL:
3388 #ifdef VMS
3389 sys$forcex (&(XFASTINT (p->pid)), 0, 1);
3390 whoosh:
3391 #endif
3392 flush_pending_output (XINT (p->infd));
3393 break;
3394 }
3395
3396 /* If we don't have process groups, send the signal to the immediate
3397 subprocess. That isn't really right, but it's better than any
3398 obvious alternative. */
3399 if (no_pgrp)
3400 {
3401 kill (XFASTINT (p->pid), signo);
3402 return;
3403 }
3404
3405 /* gid may be a pid, or minus a pgrp's number */
3406 #ifdef TIOCSIGSEND
3407 if (!NILP (current_group))
3408 ioctl (XINT (p->infd), TIOCSIGSEND, signo);
3409 else
3410 {
3411 gid = - XFASTINT (p->pid);
3412 kill (gid, signo);
3413 }
3414 #else /* ! defined (TIOCSIGSEND) */
3415 EMACS_KILLPG (-gid, signo);
3416 #endif /* ! defined (TIOCSIGSEND) */
3417 }
3418
3419 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
3420 "Interrupt process PROCESS. May be process or name of one.\n\
3421 PROCESS may be a process, a buffer, or the name of a process or buffer.\n\
3422 nil or no arg means current buffer's process.\n\
3423 Second arg CURRENT-GROUP non-nil means send signal to\n\
3424 the current process-group of the process's controlling terminal\n\
3425 rather than to the process's own process group.\n\
3426 If the process is a shell, this means interrupt current subjob\n\
3427 rather than the shell.")
3428 (process, current_group)
3429 Lisp_Object process, current_group;
3430 {
3431 process_send_signal (process, SIGINT, current_group, 0);
3432 return process;
3433 }
3434
3435 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
3436 "Kill process PROCESS. May be process or name of one.\n\
3437 See function `interrupt-process' for more details on usage.")
3438 (process, current_group)
3439 Lisp_Object process, current_group;
3440 {
3441 process_send_signal (process, SIGKILL, current_group, 0);
3442 return process;
3443 }
3444
3445 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
3446 "Send QUIT signal to process PROCESS. May be process or name of one.\n\
3447 See function `interrupt-process' for more details on usage.")
3448 (process, current_group)
3449 Lisp_Object process, current_group;
3450 {
3451 process_send_signal (process, SIGQUIT, current_group, 0);
3452 return process;
3453 }
3454
3455 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
3456 "Stop process PROCESS. May be process or name of one.\n\
3457 See function `interrupt-process' for more details on usage.")
3458 (process, current_group)
3459 Lisp_Object process, current_group;
3460 {
3461 #ifndef SIGTSTP
3462 error ("no SIGTSTP support");
3463 #else
3464 process_send_signal (process, SIGTSTP, current_group, 0);
3465 #endif
3466 return process;
3467 }
3468
3469 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
3470 "Continue process PROCESS. May be process or name of one.\n\
3471 See function `interrupt-process' for more details on usage.")
3472 (process, current_group)
3473 Lisp_Object process, current_group;
3474 {
3475 #ifdef SIGCONT
3476 process_send_signal (process, SIGCONT, current_group, 0);
3477 #else
3478 error ("no SIGCONT support");
3479 #endif
3480 return process;
3481 }
3482
3483 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
3484 2, 2, "nProcess number: \nnSignal code: ",
3485 "Send the process with process id PID the signal with code SIGCODE.\n\
3486 PID must be an integer. The process need not be a child of this Emacs.\n\
3487 SIGCODE may be an integer, or a symbol whose name is a signal name.")
3488 (pid, sigcode)
3489 Lisp_Object pid, sigcode;
3490 {
3491 CHECK_NUMBER (pid, 0);
3492
3493 #define handle_signal(NAME, VALUE) \
3494 else if (!strcmp (name, NAME)) \
3495 XSETINT (sigcode, VALUE)
3496
3497 if (INTEGERP (sigcode))
3498 ;
3499 else
3500 {
3501 unsigned char *name;
3502
3503 CHECK_SYMBOL (sigcode, 1);
3504 name = XSYMBOL (sigcode)->name->data;
3505
3506 if (0)
3507 ;
3508 #ifdef SIGHUP
3509 handle_signal ("SIGHUP", SIGHUP);
3510 #endif
3511 #ifdef SIGINT
3512 handle_signal ("SIGINT", SIGINT);
3513 #endif
3514 #ifdef SIGQUIT
3515 handle_signal ("SIGQUIT", SIGQUIT);
3516 #endif
3517 #ifdef SIGILL
3518 handle_signal ("SIGILL", SIGILL);
3519 #endif
3520 #ifdef SIGABRT
3521 handle_signal ("SIGABRT", SIGABRT);
3522 #endif
3523 #ifdef SIGEMT
3524 handle_signal ("SIGEMT", SIGEMT);
3525 #endif
3526 #ifdef SIGKILL
3527 handle_signal ("SIGKILL", SIGKILL);
3528 #endif
3529 #ifdef SIGFPE
3530 handle_signal ("SIGFPE", SIGFPE);
3531 #endif
3532 #ifdef SIGBUS
3533 handle_signal ("SIGBUS", SIGBUS);
3534 #endif
3535 #ifdef SIGSEGV
3536 handle_signal ("SIGSEGV", SIGSEGV);
3537 #endif
3538 #ifdef SIGSYS
3539 handle_signal ("SIGSYS", SIGSYS);
3540 #endif
3541 #ifdef SIGPIPE
3542 handle_signal ("SIGPIPE", SIGPIPE);
3543 #endif
3544 #ifdef SIGALRM
3545 handle_signal ("SIGALRM", SIGALRM);
3546 #endif
3547 #ifdef SIGTERM
3548 handle_signal ("SIGTERM", SIGTERM);
3549 #endif
3550 #ifdef SIGURG
3551 handle_signal ("SIGURG", SIGURG);
3552 #endif
3553 #ifdef SIGSTOP
3554 handle_signal ("SIGSTOP", SIGSTOP);
3555 #endif
3556 #ifdef SIGTSTP
3557 handle_signal ("SIGTSTP", SIGTSTP);
3558 #endif
3559 #ifdef SIGCONT
3560 handle_signal ("SIGCONT", SIGCONT);
3561 #endif
3562 #ifdef SIGCHLD
3563 handle_signal ("SIGCHLD", SIGCHLD);
3564 #endif
3565 #ifdef SIGTTIN
3566 handle_signal ("SIGTTIN", SIGTTIN);
3567 #endif
3568 #ifdef SIGTTOU
3569 handle_signal ("SIGTTOU", SIGTTOU);
3570 #endif
3571 #ifdef SIGIO
3572 handle_signal ("SIGIO", SIGIO);
3573 #endif
3574 #ifdef SIGXCPU
3575 handle_signal ("SIGXCPU", SIGXCPU);
3576 #endif
3577 #ifdef SIGXFSZ
3578 handle_signal ("SIGXFSZ", SIGXFSZ);
3579 #endif
3580 #ifdef SIGVTALRM
3581 handle_signal ("SIGVTALRM", SIGVTALRM);
3582 #endif
3583 #ifdef SIGPROF
3584 handle_signal ("SIGPROF", SIGPROF);
3585 #endif
3586 #ifdef SIGWINCH
3587 handle_signal ("SIGWINCH", SIGWINCH);
3588 #endif
3589 #ifdef SIGINFO
3590 handle_signal ("SIGINFO", SIGINFO);
3591 #endif
3592 #ifdef SIGUSR1
3593 handle_signal ("SIGUSR1", SIGUSR1);
3594 #endif
3595 #ifdef SIGUSR2
3596 handle_signal ("SIGUSR2", SIGUSR2);
3597 #endif
3598 else
3599 error ("Undefined signal name %s", name);
3600 }
3601
3602 #undef handle_signal
3603
3604 return make_number (kill (XINT (pid), XINT (sigcode)));
3605 }
3606
3607 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
3608 "Make PROCESS see end-of-file in its input.\n\
3609 Eof comes after any text already sent to it.\n\
3610 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
3611 nil, indicating the current buffer's process.\n\
3612 If PROCESS is a network connection, or is a process communicating\n\
3613 through a pipe (as opposed to a pty), then you cannot send any more\n\
3614 text to PROCESS after you call this function.")
3615 (process)
3616 Lisp_Object process;
3617 {
3618 Lisp_Object proc;
3619
3620 proc = get_process (process);
3621
3622 /* Make sure the process is really alive. */
3623 if (! NILP (XPROCESS (proc)->raw_status_low))
3624 update_status (XPROCESS (proc));
3625 if (! EQ (XPROCESS (proc)->status, Qrun))
3626 error ("Process %s not running", XSTRING (XPROCESS (proc)->name)->data);
3627
3628 #ifdef VMS
3629 send_process (proc, "\032", 1, Qnil); /* ^z */
3630 #else
3631 if (!NILP (XPROCESS (proc)->pty_flag))
3632 send_process (proc, "\004", 1, Qnil);
3633 else
3634 {
3635 #ifdef HAVE_SHUTDOWN
3636 /* If this is a network connection, or socketpair is used
3637 for communication with the subprocess, call shutdown to cause EOF.
3638 (In some old system, shutdown to socketpair doesn't work.
3639 Then we just can't win.) */
3640 if (NILP (XPROCESS (proc)->pid)
3641 || XINT (XPROCESS (proc)->outfd) == XINT (XPROCESS (proc)->infd))
3642 shutdown (XINT (XPROCESS (proc)->outfd), 1);
3643 /* In case of socketpair, outfd == infd, so don't close it. */
3644 if (XINT (XPROCESS (proc)->outfd) != XINT (XPROCESS (proc)->infd))
3645 close (XINT (XPROCESS (proc)->outfd));
3646 #else /* not HAVE_SHUTDOWN */
3647 close (XINT (XPROCESS (proc)->outfd));
3648 #endif /* not HAVE_SHUTDOWN */
3649 XSETINT (XPROCESS (proc)->outfd, open (NULL_DEVICE, O_WRONLY));
3650 }
3651 #endif /* VMS */
3652 return process;
3653 }
3654
3655 /* Kill all processes associated with `buffer'.
3656 If `buffer' is nil, kill all processes */
3657
3658 kill_buffer_processes (buffer)
3659 Lisp_Object buffer;
3660 {
3661 Lisp_Object tail, proc;
3662
3663 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCONS (tail)->cdr)
3664 {
3665 proc = XCONS (XCONS (tail)->car)->cdr;
3666 if (GC_PROCESSP (proc)
3667 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
3668 {
3669 if (NETCONN_P (proc))
3670 Fdelete_process (proc);
3671 else if (XINT (XPROCESS (proc)->infd) >= 0)
3672 process_send_signal (proc, SIGHUP, Qnil, 1);
3673 }
3674 }
3675 }
3676 \f
3677 /* On receipt of a signal that a child status has changed,
3678 loop asking about children with changed statuses until
3679 the system says there are no more.
3680 All we do is change the status;
3681 we do not run sentinels or print notifications.
3682 That is saved for the next time keyboard input is done,
3683 in order to avoid timing errors. */
3684
3685 /** WARNING: this can be called during garbage collection.
3686 Therefore, it must not be fooled by the presence of mark bits in
3687 Lisp objects. */
3688
3689 /** USG WARNING: Although it is not obvious from the documentation
3690 in signal(2), on a USG system the SIGCLD handler MUST NOT call
3691 signal() before executing at least one wait(), otherwise the handler
3692 will be called again, resulting in an infinite loop. The relevant
3693 portion of the documentation reads "SIGCLD signals will be queued
3694 and the signal-catching function will be continually reentered until
3695 the queue is empty". Invoking signal() causes the kernel to reexamine
3696 the SIGCLD queue. Fred Fish, UniSoft Systems Inc. */
3697
3698 SIGTYPE
3699 sigchld_handler (signo)
3700 int signo;
3701 {
3702 int old_errno = errno;
3703 Lisp_Object proc;
3704 register struct Lisp_Process *p;
3705 extern EMACS_TIME *input_available_clear_time;
3706
3707 #ifdef BSD4_1
3708 extern int sigheld;
3709 sigheld |= sigbit (SIGCHLD);
3710 #endif
3711
3712 while (1)
3713 {
3714 register int pid;
3715 WAITTYPE w;
3716 Lisp_Object tail;
3717
3718 #ifdef WNOHANG
3719 #ifndef WUNTRACED
3720 #define WUNTRACED 0
3721 #endif /* no WUNTRACED */
3722 /* Keep trying to get a status until we get a definitive result. */
3723 do
3724 {
3725 errno = 0;
3726 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
3727 }
3728 while (pid <= 0 && errno == EINTR);
3729
3730 if (pid <= 0)
3731 {
3732 /* A real failure. We have done all our job, so return. */
3733
3734 /* USG systems forget handlers when they are used;
3735 must reestablish each time */
3736 #if defined (USG) && !defined (POSIX_SIGNALS)
3737 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
3738 #endif
3739 #ifdef BSD4_1
3740 sigheld &= ~sigbit (SIGCHLD);
3741 sigrelse (SIGCHLD);
3742 #endif
3743 errno = old_errno;
3744 return;
3745 }
3746 #else
3747 pid = wait (&w);
3748 #endif /* no WNOHANG */
3749
3750 /* Find the process that signaled us, and record its status. */
3751
3752 p = 0;
3753 for (tail = Vprocess_alist; CONSP (tail); tail = XCONS (tail)->cdr)
3754 {
3755 proc = XCONS (XCONS (tail)->car)->cdr;
3756 p = XPROCESS (proc);
3757 if (EQ (p->childp, Qt) && XFASTINT (p->pid) == pid)
3758 break;
3759 p = 0;
3760 }
3761
3762 /* Look for an asynchronous process whose pid hasn't been filled
3763 in yet. */
3764 if (p == 0)
3765 for (tail = Vprocess_alist; CONSP (tail); tail = XCONS (tail)->cdr)
3766 {
3767 proc = XCONS (XCONS (tail)->car)->cdr;
3768 p = XPROCESS (proc);
3769 if (INTEGERP (p->pid) && XINT (p->pid) == -1)
3770 break;
3771 p = 0;
3772 }
3773
3774 /* Change the status of the process that was found. */
3775 if (p != 0)
3776 {
3777 union { int i; WAITTYPE wt; } u;
3778 int clear_desc_flag = 0;
3779
3780 XSETINT (p->tick, ++process_tick);
3781 u.wt = w;
3782 XSETINT (p->raw_status_low, u.i & 0xffff);
3783 XSETINT (p->raw_status_high, u.i >> 16);
3784
3785 /* If process has terminated, stop waiting for its output. */
3786 if ((WIFSIGNALED (w) || WIFEXITED (w))
3787 && XINT (p->infd) >= 0)
3788 clear_desc_flag = 1;
3789
3790 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
3791 if (clear_desc_flag)
3792 {
3793 FD_CLR (XINT (p->infd), &input_wait_mask);
3794 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
3795 }
3796
3797 /* Tell wait_reading_process_input that it needs to wake up and
3798 look around. */
3799 if (input_available_clear_time)
3800 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
3801 }
3802
3803 /* There was no asynchronous process found for that id. Check
3804 if we have a synchronous process. */
3805 else
3806 {
3807 synch_process_alive = 0;
3808
3809 /* Report the status of the synchronous process. */
3810 if (WIFEXITED (w))
3811 synch_process_retcode = WRETCODE (w);
3812 else if (WIFSIGNALED (w))
3813 {
3814 int code = WTERMSIG (w);
3815 char *signame = 0;
3816
3817 if (code < NSIG)
3818 {
3819 #ifndef VMS
3820 /* Suppress warning if the table has const char *. */
3821 signame = (char *) sys_siglist[code];
3822 #else
3823 signame = sys_errlist[code];
3824 #endif
3825 }
3826 if (signame == 0)
3827 signame = "unknown";
3828
3829 synch_process_death = signame;
3830 }
3831
3832 /* Tell wait_reading_process_input that it needs to wake up and
3833 look around. */
3834 if (input_available_clear_time)
3835 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
3836 }
3837
3838 /* On some systems, we must return right away.
3839 If any more processes want to signal us, we will
3840 get another signal.
3841 Otherwise (on systems that have WNOHANG), loop around
3842 to use up all the processes that have something to tell us. */
3843 #if defined (USG) && ! (defined (HPUX) && defined (WNOHANG)) || defined (WINDOWSNT)
3844 #if defined (USG) && ! defined (POSIX_SIGNALS)
3845 signal (signo, sigchld_handler);
3846 #endif
3847 errno = old_errno;
3848 return;
3849 #endif /* USG, but not HPUX with WNOHANG */
3850 }
3851 }
3852 \f
3853
3854 static Lisp_Object
3855 exec_sentinel_unwind (data)
3856 Lisp_Object data;
3857 {
3858 XPROCESS (XCONS (data)->car)->sentinel = XCONS (data)->cdr;
3859 return Qnil;
3860 }
3861
3862 static Lisp_Object
3863 exec_sentinel_error_handler (error)
3864 Lisp_Object error;
3865 {
3866 cmd_error_internal (error, "error in process sentinel: ");
3867 Vinhibit_quit = Qt;
3868 update_echo_area ();
3869 Fsleep_for (make_number (2), Qnil);
3870 }
3871
3872 static void
3873 exec_sentinel (proc, reason)
3874 Lisp_Object proc, reason;
3875 {
3876 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
3877 register struct Lisp_Process *p = XPROCESS (proc);
3878 int count = specpdl_ptr - specpdl;
3879 int outer_running_asynch_code = running_asynch_code;
3880
3881 /* No need to gcpro these, because all we do with them later
3882 is test them for EQness, and none of them should be a string. */
3883 odeactivate = Vdeactivate_mark;
3884 XSETBUFFER (obuffer, current_buffer);
3885 okeymap = current_buffer->keymap;
3886
3887 sentinel = p->sentinel;
3888 if (NILP (sentinel))
3889 return;
3890
3891 /* Zilch the sentinel while it's running, to avoid recursive invocations;
3892 assure that it gets restored no matter how the sentinel exits. */
3893 p->sentinel = Qnil;
3894 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
3895 /* Inhibit quit so that random quits don't screw up a running filter. */
3896 specbind (Qinhibit_quit, Qt);
3897 specbind (Qlast_nonmenu_event, Qt);
3898
3899 /* In case we get recursively called,
3900 and we already saved the match data nonrecursively,
3901 save the same match data in safely recursive fashion. */
3902 if (outer_running_asynch_code)
3903 {
3904 Lisp_Object tem;
3905 tem = Fmatch_data (Qnil, Qnil);
3906 restore_match_data ();
3907 record_unwind_protect (Fstore_match_data, Fmatch_data (Qnil, Qnil));
3908 Fstore_match_data (tem);
3909 }
3910
3911 /* For speed, if a search happens within this code,
3912 save the match data in a special nonrecursive fashion. */
3913 running_asynch_code = 1;
3914
3915 internal_condition_case_1 (read_process_output_call,
3916 Fcons (sentinel,
3917 Fcons (proc, Fcons (reason, Qnil))),
3918 !NILP (Vdebug_on_error) ? Qnil : Qerror,
3919 exec_sentinel_error_handler);
3920
3921 /* If we saved the match data nonrecursively, restore it now. */
3922 restore_match_data ();
3923 running_asynch_code = outer_running_asynch_code;
3924
3925 Vdeactivate_mark = odeactivate;
3926 #if 0
3927 if (! EQ (Fcurrent_buffer (), obuffer)
3928 || ! EQ (current_buffer->keymap, okeymap))
3929 #endif
3930 /* But do it only if the caller is actually going to read events.
3931 Otherwise there's no need to make him wake up, and it could
3932 cause trouble (for example it would make Fsit_for return). */
3933 if (waiting_for_user_input_p == -1)
3934 record_asynch_buffer_change ();
3935
3936 unbind_to (count, Qnil);
3937 }
3938
3939 /* Report all recent events of a change in process status
3940 (either run the sentinel or output a message).
3941 This is done while Emacs is waiting for keyboard input. */
3942
3943 status_notify ()
3944 {
3945 register Lisp_Object proc, buffer;
3946 Lisp_Object tail, msg;
3947 struct gcpro gcpro1, gcpro2;
3948
3949 tail = Qnil;
3950 msg = Qnil;
3951 /* We need to gcpro tail; if read_process_output calls a filter
3952 which deletes a process and removes the cons to which tail points
3953 from Vprocess_alist, and then causes a GC, tail is an unprotected
3954 reference. */
3955 GCPRO2 (tail, msg);
3956
3957 /* Set this now, so that if new processes are created by sentinels
3958 that we run, we get called again to handle their status changes. */
3959 update_tick = process_tick;
3960
3961 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
3962 {
3963 Lisp_Object symbol;
3964 register struct Lisp_Process *p;
3965
3966 proc = Fcdr (Fcar (tail));
3967 p = XPROCESS (proc);
3968
3969 if (XINT (p->tick) != XINT (p->update_tick))
3970 {
3971 XSETINT (p->update_tick, XINT (p->tick));
3972
3973 /* If process is still active, read any output that remains. */
3974 while (! EQ (p->filter, Qt)
3975 && XINT (p->infd) >= 0
3976 && read_process_output (proc, XINT (p->infd)) > 0);
3977
3978 buffer = p->buffer;
3979
3980 /* Get the text to use for the message. */
3981 if (!NILP (p->raw_status_low))
3982 update_status (p);
3983 msg = status_message (p->status);
3984
3985 /* If process is terminated, deactivate it or delete it. */
3986 symbol = p->status;
3987 if (CONSP (p->status))
3988 symbol = XCONS (p->status)->car;
3989
3990 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
3991 || EQ (symbol, Qclosed))
3992 {
3993 if (delete_exited_processes)
3994 remove_process (proc);
3995 else
3996 deactivate_process (proc);
3997 }
3998
3999 /* The actions above may have further incremented p->tick.
4000 So set p->update_tick again
4001 so that an error in the sentinel will not cause
4002 this code to be run again. */
4003 XSETINT (p->update_tick, XINT (p->tick));
4004 /* Now output the message suitably. */
4005 if (!NILP (p->sentinel))
4006 exec_sentinel (proc, msg);
4007 /* Don't bother with a message in the buffer
4008 when a process becomes runnable. */
4009 else if (!EQ (symbol, Qrun) && !NILP (buffer))
4010 {
4011 Lisp_Object ro, tem;
4012 struct buffer *old = current_buffer;
4013 int opoint;
4014 int before;
4015
4016 ro = XBUFFER (buffer)->read_only;
4017
4018 /* Avoid error if buffer is deleted
4019 (probably that's why the process is dead, too) */
4020 if (NILP (XBUFFER (buffer)->name))
4021 continue;
4022 Fset_buffer (buffer);
4023
4024 opoint = PT;
4025 /* Insert new output into buffer
4026 at the current end-of-output marker,
4027 thus preserving logical ordering of input and output. */
4028 if (XMARKER (p->mark)->buffer)
4029 SET_PT (marker_position (p->mark));
4030 else
4031 SET_PT (ZV);
4032
4033 before = PT;
4034
4035 tem = current_buffer->read_only;
4036 current_buffer->read_only = Qnil;
4037 insert_string ("\nProcess ");
4038 Finsert (1, &p->name);
4039 insert_string (" ");
4040 Finsert (1, &msg);
4041 current_buffer->read_only = tem;
4042 Fset_marker (p->mark, make_number (PT), p->buffer);
4043
4044 if (opoint >= before)
4045 SET_PT (opoint + (PT - before));
4046 else
4047 SET_PT (opoint);
4048
4049 set_buffer_internal (old);
4050 }
4051 }
4052 } /* end for */
4053
4054 update_mode_lines++; /* in case buffers use %s in mode-line-format */
4055 redisplay_preserve_echo_area ();
4056
4057 UNGCPRO;
4058 }
4059
4060 \f
4061 DEFUN ("set-process-coding-system", Fset_process_coding_system,
4062 Sset_process_coding_system, 1, 3, 0,
4063 "Set coding-systems of PROCESS to DECODING (input from the process) and\n\
4064 ENCODING (output to the process).")
4065 (proc, decoding, encoding)
4066 register Lisp_Object proc, decoding, encoding;
4067 {
4068 register struct Lisp_Process *p;
4069
4070 CHECK_PROCESS (proc, 0);
4071 p = XPROCESS (proc);
4072 if (XINT (p->infd) < 0)
4073 error ("Input file descriptor of %s closed", XSTRING (p->name)->data);
4074 if (XINT (p->outfd) < 0)
4075 error ("Output file descriptor of %s closed", XSTRING (p->name)->data);
4076
4077 p->decode_coding_system = Fcheck_coding_system (decoding);
4078 p->encode_coding_system = Fcheck_coding_system (encoding);
4079 setup_coding_system (decoding,
4080 proc_decode_coding_system[XINT (p->infd)]);
4081 setup_coding_system (encoding,
4082 proc_encode_coding_system[XINT (p->outfd)]);
4083
4084 return Qnil;
4085 }
4086
4087 DEFUN ("process-coding-system",
4088 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
4089 "Return a cons of coding-system for decoding and encoding of PROCESS.")
4090 (proc)
4091 register Lisp_Object proc;
4092 {
4093 CHECK_PROCESS (proc, 0);
4094 return Fcons (XPROCESS (proc)->decode_coding_system,
4095 XPROCESS (proc)->encode_coding_system);
4096 }
4097 \f
4098 /* The first time this is called, assume keyboard input comes from DESC
4099 instead of from where we used to expect it.
4100 Subsequent calls mean assume input keyboard can come from DESC
4101 in addition to other places. */
4102
4103 static int add_keyboard_wait_descriptor_called_flag;
4104
4105 void
4106 add_keyboard_wait_descriptor (desc)
4107 int desc;
4108 {
4109 if (! add_keyboard_wait_descriptor_called_flag)
4110 FD_CLR (0, &input_wait_mask);
4111 add_keyboard_wait_descriptor_called_flag = 1;
4112 FD_SET (desc, &input_wait_mask);
4113 FD_SET (desc, &non_process_wait_mask);
4114 if (desc > max_keyboard_desc)
4115 max_keyboard_desc = desc;
4116 }
4117
4118 /* From now on, do not expect DESC to give keyboard input. */
4119
4120 void
4121 delete_keyboard_wait_descriptor (desc)
4122 int desc;
4123 {
4124 int fd;
4125 int lim = max_keyboard_desc;
4126
4127 FD_CLR (desc, &input_wait_mask);
4128 FD_CLR (desc, &non_process_wait_mask);
4129
4130 if (desc == max_keyboard_desc)
4131 for (fd = 0; fd < lim; fd++)
4132 if (FD_ISSET (fd, &input_wait_mask)
4133 && !FD_ISSET (fd, &non_keyboard_wait_mask))
4134 max_keyboard_desc = fd;
4135 }
4136
4137 /* Return nonzero if *MASK has a bit set
4138 that corresponds to one of the keyboard input descriptors. */
4139
4140 int
4141 keyboard_bit_set (mask)
4142 SELECT_TYPE *mask;
4143 {
4144 int fd;
4145
4146 for (fd = 0; fd <= max_keyboard_desc; fd++)
4147 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
4148 && !FD_ISSET (fd, &non_keyboard_wait_mask))
4149 return 1;
4150
4151 return 0;
4152 }
4153 \f
4154 init_process ()
4155 {
4156 register int i;
4157
4158 #ifdef SIGCHLD
4159 #ifndef CANNOT_DUMP
4160 if (! noninteractive || initialized)
4161 #endif
4162 signal (SIGCHLD, sigchld_handler);
4163 #endif
4164
4165 FD_ZERO (&input_wait_mask);
4166 FD_ZERO (&non_keyboard_wait_mask);
4167 FD_ZERO (&non_process_wait_mask);
4168 max_process_desc = 0;
4169
4170 FD_SET (0, &input_wait_mask);
4171
4172 Vprocess_alist = Qnil;
4173 for (i = 0; i < MAXDESC; i++)
4174 {
4175 chan_process[i] = Qnil;
4176 proc_buffered_char[i] = -1;
4177 }
4178 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
4179 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
4180 }
4181
4182 syms_of_process ()
4183 {
4184 Qprocessp = intern ("processp");
4185 staticpro (&Qprocessp);
4186 Qrun = intern ("run");
4187 staticpro (&Qrun);
4188 Qstop = intern ("stop");
4189 staticpro (&Qstop);
4190 Qsignal = intern ("signal");
4191 staticpro (&Qsignal);
4192
4193 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
4194 here again.
4195
4196 Qexit = intern ("exit");
4197 staticpro (&Qexit); */
4198
4199 Qopen = intern ("open");
4200 staticpro (&Qopen);
4201 Qclosed = intern ("closed");
4202 staticpro (&Qclosed);
4203
4204 Qlast_nonmenu_event = intern ("last-nonmenu-event");
4205 staticpro (&Qlast_nonmenu_event);
4206
4207 staticpro (&Vprocess_alist);
4208
4209 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
4210 "*Non-nil means delete processes immediately when they exit.\n\
4211 nil means don't delete them until `list-processes' is run.");
4212
4213 delete_exited_processes = 1;
4214
4215 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
4216 "Control type of device used to communicate with subprocesses.\n\
4217 Values are nil to use a pipe, or t or `pty' to use a pty.\n\
4218 The value has no effect if the system has no ptys or if all ptys are busy:\n\
4219 then a pipe is used in any case.\n\
4220 The value takes effect when `start-process' is called.");
4221 Vprocess_connection_type = Qt;
4222
4223 defsubr (&Sprocessp);
4224 defsubr (&Sget_process);
4225 defsubr (&Sget_buffer_process);
4226 defsubr (&Sdelete_process);
4227 defsubr (&Sprocess_status);
4228 defsubr (&Sprocess_exit_status);
4229 defsubr (&Sprocess_id);
4230 defsubr (&Sprocess_name);
4231 defsubr (&Sprocess_tty_name);
4232 defsubr (&Sprocess_command);
4233 defsubr (&Sset_process_buffer);
4234 defsubr (&Sprocess_buffer);
4235 defsubr (&Sprocess_mark);
4236 defsubr (&Sset_process_filter);
4237 defsubr (&Sprocess_filter);
4238 defsubr (&Sset_process_sentinel);
4239 defsubr (&Sprocess_sentinel);
4240 defsubr (&Sset_process_window_size);
4241 defsubr (&Sprocess_kill_without_query);
4242 defsubr (&Sprocess_contact);
4243 defsubr (&Slist_processes);
4244 defsubr (&Sprocess_list);
4245 defsubr (&Sstart_process);
4246 #ifdef HAVE_SOCKETS
4247 defsubr (&Sopen_network_stream);
4248 #endif /* HAVE_SOCKETS */
4249 defsubr (&Saccept_process_output);
4250 defsubr (&Sprocess_send_region);
4251 defsubr (&Sprocess_send_string);
4252 defsubr (&Sinterrupt_process);
4253 defsubr (&Skill_process);
4254 defsubr (&Squit_process);
4255 defsubr (&Sstop_process);
4256 defsubr (&Scontinue_process);
4257 defsubr (&Sprocess_send_eof);
4258 defsubr (&Ssignal_process);
4259 defsubr (&Swaiting_for_user_input_p);
4260 /* defsubr (&Sprocess_connection); */
4261 defsubr (&Sset_process_coding_system);
4262 defsubr (&Sprocess_coding_system);
4263 }
4264
4265 \f
4266 #else /* not subprocesses */
4267
4268 #include <sys/types.h>
4269 #include <errno.h>
4270
4271 #include "lisp.h"
4272 #include "systime.h"
4273 #include "termopts.h"
4274 #include "sysselect.h"
4275
4276 extern int frame_garbaged;
4277
4278 extern EMACS_TIME timer_check ();
4279 extern int timers_run;
4280
4281 /* As described above, except assuming that there are no subprocesses:
4282
4283 Wait for timeout to elapse and/or keyboard input to be available.
4284
4285 time_limit is:
4286 timeout in seconds, or
4287 zero for no limit, or
4288 -1 means gobble data immediately available but don't wait for any.
4289
4290 read_kbd is a Lisp_Object:
4291 0 to ignore keyboard input, or
4292 1 to return when input is available, or
4293 -1 means caller will actually read the input, so don't throw to
4294 the quit handler.
4295 a cons cell, meaning wait until its car is non-nil
4296 (and gobble terminal input into the buffer if any arrives), or
4297 We know that read_kbd will never be a Lisp_Process, since
4298 `subprocesses' isn't defined.
4299
4300 do_display != 0 means redisplay should be done to show subprocess
4301 output that arrives.
4302
4303 Return true iff we received input from any process. */
4304
4305 int
4306 wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
4307 int time_limit, microsecs;
4308 Lisp_Object read_kbd;
4309 int do_display;
4310 {
4311 EMACS_TIME end_time, timeout;
4312 SELECT_TYPE waitchannels;
4313 int xerrno;
4314 Lisp_Object *wait_for_cell = 0;
4315
4316 /* If waiting for non-nil in a cell, record where. */
4317 if (CONSP (read_kbd))
4318 {
4319 wait_for_cell = &XCONS (read_kbd)->car;
4320 XSETFASTINT (read_kbd, 0);
4321 }
4322
4323 /* What does time_limit really mean? */
4324 if (time_limit || microsecs)
4325 {
4326 if (time_limit == -1)
4327 /* In fact, it's zero. */
4328 EMACS_SET_SECS_USECS (timeout, 0, 0);
4329 else
4330 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4331
4332 /* How far in the future is that? */
4333 EMACS_GET_TIME (end_time);
4334 EMACS_ADD_TIME (end_time, end_time, timeout);
4335 }
4336 else
4337 /* It's infinite. */
4338 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4339
4340 /* Turn off periodic alarms (in case they are in use)
4341 because the select emulator uses alarms. */
4342 stop_polling ();
4343
4344 for (;;)
4345 {
4346 int nfds;
4347 int timeout_reduced_for_timers = 0;
4348
4349 /* If calling from keyboard input, do not quit
4350 since we want to return C-g as an input character.
4351 Otherwise, do pending quit if requested. */
4352 if (XINT (read_kbd) >= 0)
4353 QUIT;
4354
4355 /* Exit now if the cell we're waiting for became non-nil. */
4356 if (wait_for_cell && ! NILP (*wait_for_cell))
4357 break;
4358
4359 /* Compute time from now till when time limit is up */
4360 /* Exit if already run out */
4361 if (time_limit > 0 || microsecs)
4362 {
4363 EMACS_GET_TIME (timeout);
4364 EMACS_SUB_TIME (timeout, end_time, timeout);
4365 if (EMACS_TIME_NEG_P (timeout))
4366 break;
4367 }
4368
4369 /* If our caller will not immediately handle keyboard events,
4370 run timer events directly.
4371 (Callers that will immediately read keyboard events
4372 call timer_delay on their own.) */
4373 if (! wait_for_cell)
4374 {
4375 EMACS_TIME timer_delay;
4376 int old_timers_run;
4377
4378 retry:
4379 old_timers_run = timers_run;
4380 timer_delay = timer_check (1);
4381 if (timers_run != old_timers_run && do_display)
4382 {
4383 redisplay_preserve_echo_area ();
4384 /* We must retry, since a timer may have requeued itself
4385 and that could alter the time delay. */
4386 goto retry;
4387 }
4388
4389 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4390 {
4391 EMACS_TIME difference;
4392 EMACS_SUB_TIME (difference, timer_delay, timeout);
4393 if (EMACS_TIME_NEG_P (difference))
4394 {
4395 timeout = timer_delay;
4396 timeout_reduced_for_timers = 1;
4397 }
4398 }
4399 }
4400
4401 /* Cause C-g and alarm signals to take immediate action,
4402 and cause input available signals to zero out timeout. */
4403 if (XINT (read_kbd) < 0)
4404 set_waiting_for_input (&timeout);
4405
4406 /* Wait till there is something to do. */
4407
4408 if (! XINT (read_kbd) && wait_for_cell == 0)
4409 FD_ZERO (&waitchannels);
4410 else
4411 FD_SET (0, &waitchannels);
4412
4413 /* If a frame has been newly mapped and needs updating,
4414 reprocess its display stuff. */
4415 if (frame_garbaged && do_display)
4416 {
4417 clear_waiting_for_input ();
4418 redisplay_preserve_echo_area ();
4419 if (XINT (read_kbd) < 0)
4420 set_waiting_for_input (&timeout);
4421 }
4422
4423 if (XINT (read_kbd) && detect_input_pending ())
4424 {
4425 nfds = 0;
4426 FD_ZERO (&waitchannels);
4427 }
4428 else
4429 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4430 &timeout);
4431
4432 xerrno = errno;
4433
4434 /* Make C-g and alarm signals set flags again */
4435 clear_waiting_for_input ();
4436
4437 /* If we woke up due to SIGWINCH, actually change size now. */
4438 do_pending_window_change ();
4439
4440 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4441 /* We waited the full specified time, so return now. */
4442 break;
4443
4444 if (nfds == -1)
4445 {
4446 /* If the system call was interrupted, then go around the
4447 loop again. */
4448 if (xerrno == EINTR)
4449 FD_ZERO (&waitchannels);
4450 else
4451 error ("select error: %s", strerror (xerrno));
4452 }
4453 #ifdef sun
4454 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
4455 /* System sometimes fails to deliver SIGIO. */
4456 kill (getpid (), SIGIO);
4457 #endif
4458 #ifdef SIGIO
4459 if (XINT (read_kbd) && interrupt_input && (waitchannels & 1))
4460 kill (getpid (), SIGIO);
4461 #endif
4462
4463 /* Check for keyboard input */
4464
4465 if ((XINT (read_kbd) != 0)
4466 && detect_input_pending_run_timers (do_display))
4467 {
4468 swallow_events (do_display);
4469 if (detect_input_pending_run_timers (do_display))
4470 break;
4471 }
4472
4473 /* If wait_for_cell. check for keyboard input
4474 but don't run any timers.
4475 ??? (It seems wrong to me to check for keyboard
4476 input at all when wait_for_cell, but the code
4477 has been this way since July 1994.
4478 Try changing this after version 19.31.) */
4479 if (wait_for_cell
4480 && detect_input_pending ())
4481 {
4482 swallow_events (do_display);
4483 if (detect_input_pending ())
4484 break;
4485 }
4486
4487 /* Exit now if the cell we're waiting for became non-nil. */
4488 if (wait_for_cell && ! NILP (*wait_for_cell))
4489 break;
4490 }
4491
4492 start_polling ();
4493
4494 return 0;
4495 }
4496
4497
4498 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
4499 /* Don't confuse make-docfile by having two doc strings for this function.
4500 make-docfile does not pay attention to #if, for good reason! */
4501 0)
4502 (name)
4503 register Lisp_Object name;
4504 {
4505 return Qnil;
4506 }
4507
4508 /* Kill all processes associated with `buffer'.
4509 If `buffer' is nil, kill all processes.
4510 Since we have no subprocesses, this does nothing. */
4511
4512 kill_buffer_processes (buffer)
4513 Lisp_Object buffer;
4514 {
4515 }
4516
4517 init_process ()
4518 {
4519 }
4520
4521 syms_of_process ()
4522 {
4523 defsubr (&Sget_buffer_process);
4524 }
4525
4526 \f
4527 #endif /* not subprocesses */