(#includes): Allow compilation with only Xaw.
[emacs.git] / src / process.c
blob9fa3c19df2d58a8f9682a11c7893b6fd99746fb9
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 86, 87, 88, 93, 94, 95, 96, 98, 1999
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
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.
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.
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. */
23 #define _GNU_SOURCE /* to get strsignal declared with glibc 2 */
24 #include <config.h>
25 #include <signal.h>
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. */
35 #ifdef subprocesses
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
47 #ifdef WINDOWSNT
48 #include <stdlib.h>
49 #include <fcntl.h>
50 #endif /* not WINDOWSNT */
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 */
62 /* TERM is a poor-man's SLIP, used on GNU/Linux. */
63 #ifdef TERM
64 #include <client.h>
65 #endif
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
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 */
83 #ifdef BROKEN_O_NONBLOCK
84 #undef O_NONBLOCK
85 #endif /* BROKEN_O_NONBLOCK */
87 #ifdef NEED_BSDTTY
88 #include <bsdtty.h>
89 #endif
91 #ifdef IRIS
92 #include <sys/sysmacros.h> /* for "minor" */
93 #endif /* not IRIS */
95 #include "systime.h"
96 #include "systty.h"
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 #include "keyboard.h"
110 #include "dispextern.h"
112 #define max(a, b) ((a) > (b) ? (a) : (b))
114 Lisp_Object Qprocessp;
115 Lisp_Object Qrun, Qstop, Qsignal, Qopen, Qclosed;
116 Lisp_Object Qlast_nonmenu_event;
117 /* Qexit is declared and initialized in eval.c. */
119 /* a process object is a network connection when its childp field is neither
120 Qt nor Qnil but is instead a cons cell (HOSTNAME PORTNUM). */
122 #ifdef HAVE_SOCKETS
123 #define NETCONN_P(p) (GC_CONSP (XPROCESS (p)->childp))
124 #else
125 #define NETCONN_P(p) 0
126 #endif /* HAVE_SOCKETS */
128 /* Define first descriptor number available for subprocesses. */
129 #ifdef VMS
130 #define FIRST_PROC_DESC 1
131 #else /* Not VMS */
132 #define FIRST_PROC_DESC 3
133 #endif
135 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
136 testing SIGCHLD. */
138 #if !defined (SIGCHLD) && defined (SIGCLD)
139 #define SIGCHLD SIGCLD
140 #endif /* SIGCLD */
142 #include "syssignal.h"
144 #include "syswait.h"
146 extern void set_waiting_for_input P_ ((EMACS_TIME *));
148 extern int errno;
149 #ifdef VMS
150 extern char *sys_errlist[];
151 #endif
153 #ifndef HAVE_H_ERRNO
154 extern int h_errno;
155 #endif
157 /* t means use pty, nil means use a pipe,
158 maybe other values to come. */
159 static Lisp_Object Vprocess_connection_type;
161 #ifdef SKTPAIR
162 #ifndef HAVE_SOCKETS
163 #include <sys/socket.h>
164 #endif
165 #endif /* SKTPAIR */
167 /* These next two vars are non-static since sysdep.c uses them in the
168 emulation of `select'. */
169 /* Number of events of change of status of a process. */
170 int process_tick;
171 /* Number of events for which the user or sentinel has been notified. */
172 int update_tick;
174 #include "sysselect.h"
176 extern int keyboard_bit_set P_ ((SELECT_TYPE *));
178 /* If we support a window system, turn on the code to poll periodically
179 to detect C-g. It isn't actually used when doing interrupt input. */
180 #ifdef HAVE_WINDOW_SYSTEM
181 #define POLL_FOR_INPUT
182 #endif
184 /* Mask of bits indicating the descriptors that we wait for input on. */
186 static SELECT_TYPE input_wait_mask;
188 /* Mask that excludes keyboard input descriptor (s). */
190 static SELECT_TYPE non_keyboard_wait_mask;
192 /* Mask that excludes process input descriptor (s). */
194 static SELECT_TYPE non_process_wait_mask;
196 /* The largest descriptor currently in use for a process object. */
197 static int max_process_desc;
199 /* The largest descriptor currently in use for keyboard input. */
200 static int max_keyboard_desc;
202 /* Nonzero means delete a process right away if it exits. */
203 static int delete_exited_processes;
205 /* Indexed by descriptor, gives the process (if any) for that descriptor */
206 Lisp_Object chan_process[MAXDESC];
208 /* Alist of elements (NAME . PROCESS) */
209 Lisp_Object Vprocess_alist;
211 /* Buffered-ahead input char from process, indexed by channel.
212 -1 means empty (no char is buffered).
213 Used on sys V where the only way to tell if there is any
214 output from the process is to read at least one char.
215 Always -1 on systems that support FIONREAD. */
217 /* Don't make static; need to access externally. */
218 int proc_buffered_char[MAXDESC];
220 /* Table of `struct coding-system' for each process. */
221 static struct coding_system *proc_decode_coding_system[MAXDESC];
222 static struct coding_system *proc_encode_coding_system[MAXDESC];
224 static Lisp_Object get_process ();
226 extern EMACS_TIME timer_check ();
227 extern int timers_run;
229 /* Maximum number of bytes to send to a pty without an eof. */
230 static int pty_max_bytes;
232 extern Lisp_Object Vfile_name_coding_system, Vdefault_file_name_coding_system;
234 #ifdef HAVE_PTYS
235 /* The file name of the pty opened by allocate_pty. */
237 static char pty_name[24];
238 #endif
240 /* Compute the Lisp form of the process status, p->status, from
241 the numeric status that was returned by `wait'. */
243 Lisp_Object status_convert ();
245 void
246 update_status (p)
247 struct Lisp_Process *p;
249 union { int i; WAITTYPE wt; } u;
250 u.i = XFASTINT (p->raw_status_low) + (XFASTINT (p->raw_status_high) << 16);
251 p->status = status_convert (u.wt);
252 p->raw_status_low = Qnil;
253 p->raw_status_high = Qnil;
256 /* Convert a process status word in Unix format to
257 the list that we use internally. */
259 Lisp_Object
260 status_convert (w)
261 WAITTYPE w;
263 if (WIFSTOPPED (w))
264 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
265 else if (WIFEXITED (w))
266 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
267 WCOREDUMP (w) ? Qt : Qnil));
268 else if (WIFSIGNALED (w))
269 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
270 WCOREDUMP (w) ? Qt : Qnil));
271 else
272 return Qrun;
275 /* Given a status-list, extract the three pieces of information
276 and store them individually through the three pointers. */
278 void
279 decode_status (l, symbol, code, coredump)
280 Lisp_Object l;
281 Lisp_Object *symbol;
282 int *code;
283 int *coredump;
285 Lisp_Object tem;
287 if (SYMBOLP (l))
289 *symbol = l;
290 *code = 0;
291 *coredump = 0;
293 else
295 *symbol = XCAR (l);
296 tem = XCDR (l);
297 *code = XFASTINT (XCAR (tem));
298 tem = XCDR (tem);
299 *coredump = !NILP (tem);
303 /* Return a string describing a process status list. */
305 Lisp_Object
306 status_message (status)
307 Lisp_Object status;
309 Lisp_Object symbol;
310 int code, coredump;
311 Lisp_Object string, string2;
313 decode_status (status, &symbol, &code, &coredump);
315 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
317 char *signame;
318 synchronize_system_messages_locale ();
319 signame = strsignal (code);
320 if (signame == 0)
321 signame = "unknown";
322 string = build_string (signame);
323 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
324 XSTRING (string)->data[0] = DOWNCASE (XSTRING (string)->data[0]);
325 return concat2 (string, string2);
327 else if (EQ (symbol, Qexit))
329 if (code == 0)
330 return build_string ("finished\n");
331 string = Fnumber_to_string (make_number (code));
332 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
333 return concat2 (build_string ("exited abnormally with code "),
334 concat2 (string, string2));
336 else
337 return Fcopy_sequence (Fsymbol_name (symbol));
340 #ifdef HAVE_PTYS
342 /* Open an available pty, returning a file descriptor.
343 Return -1 on failure.
344 The file name of the terminal corresponding to the pty
345 is left in the variable pty_name. */
348 allocate_pty ()
350 struct stat stb;
351 register int c, i;
352 int fd;
354 /* Some systems name their pseudoterminals so that there are gaps in
355 the usual sequence - for example, on HP9000/S700 systems, there
356 are no pseudoterminals with names ending in 'f'. So we wait for
357 three failures in a row before deciding that we've reached the
358 end of the ptys. */
359 int failed_count = 0;
361 #ifdef PTY_ITERATION
362 PTY_ITERATION
363 #else
364 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
365 for (i = 0; i < 16; i++)
366 #endif
368 #ifdef PTY_NAME_SPRINTF
369 PTY_NAME_SPRINTF
370 #else
371 sprintf (pty_name, "/dev/pty%c%x", c, i);
372 #endif /* no PTY_NAME_SPRINTF */
374 #ifdef PTY_OPEN
375 PTY_OPEN;
376 #else /* no PTY_OPEN */
377 #ifdef IRIS
378 /* Unusual IRIS code */
379 *ptyv = emacs_open ("/dev/ptc", O_RDWR | O_NDELAY, 0);
380 if (fd < 0)
381 return -1;
382 if (fstat (fd, &stb) < 0)
383 return -1;
384 #else /* not IRIS */
385 if (stat (pty_name, &stb) < 0)
387 failed_count++;
388 if (failed_count >= 3)
389 return -1;
391 else
392 failed_count = 0;
393 #ifdef O_NONBLOCK
394 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
395 #else
396 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
397 #endif
398 #endif /* not IRIS */
399 #endif /* no PTY_OPEN */
401 if (fd >= 0)
403 /* check to make certain that both sides are available
404 this avoids a nasty yet stupid bug in rlogins */
405 #ifdef PTY_TTY_NAME_SPRINTF
406 PTY_TTY_NAME_SPRINTF
407 #else
408 sprintf (pty_name, "/dev/tty%c%x", c, i);
409 #endif /* no PTY_TTY_NAME_SPRINTF */
410 #ifndef UNIPLUS
411 if (access (pty_name, 6) != 0)
413 emacs_close (fd);
414 #if !defined(IRIS) && !defined(__sgi)
415 continue;
416 #else
417 return -1;
418 #endif /* IRIS */
420 #endif /* not UNIPLUS */
421 setup_pty (fd);
422 return fd;
425 return -1;
427 #endif /* HAVE_PTYS */
429 Lisp_Object
430 make_process (name)
431 Lisp_Object name;
433 struct Lisp_Vector *vec;
434 register Lisp_Object val, tem, name1;
435 register struct Lisp_Process *p;
436 char suffix[10];
437 register int i;
439 vec = allocate_vectorlike ((EMACS_INT) VECSIZE (struct Lisp_Process));
440 for (i = 0; i < VECSIZE (struct Lisp_Process); i++)
441 vec->contents[i] = Qnil;
442 vec->size = VECSIZE (struct Lisp_Process);
443 p = (struct Lisp_Process *)vec;
445 XSETINT (p->infd, -1);
446 XSETINT (p->outfd, -1);
447 XSETFASTINT (p->pid, 0);
448 XSETFASTINT (p->tick, 0);
449 XSETFASTINT (p->update_tick, 0);
450 p->raw_status_low = Qnil;
451 p->raw_status_high = Qnil;
452 p->status = Qrun;
453 p->mark = Fmake_marker ();
455 /* If name is already in use, modify it until it is unused. */
457 name1 = name;
458 for (i = 1; ; i++)
460 tem = Fget_process (name1);
461 if (NILP (tem)) break;
462 sprintf (suffix, "<%d>", i);
463 name1 = concat2 (name, build_string (suffix));
465 name = name1;
466 p->name = name;
467 XSETPROCESS (val, p);
468 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
469 return val;
472 void
473 remove_process (proc)
474 register Lisp_Object proc;
476 register Lisp_Object pair;
478 pair = Frassq (proc, Vprocess_alist);
479 Vprocess_alist = Fdelq (pair, Vprocess_alist);
481 deactivate_process (proc);
484 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
485 "Return t if OBJECT is a process.")
486 (object)
487 Lisp_Object object;
489 return PROCESSP (object) ? Qt : Qnil;
492 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
493 "Return the process named NAME, or nil if there is none.")
494 (name)
495 register Lisp_Object name;
497 if (PROCESSP (name))
498 return name;
499 CHECK_STRING (name, 0);
500 return Fcdr (Fassoc (name, Vprocess_alist));
503 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
504 "Return the (or a) process associated with BUFFER.\n\
505 BUFFER may be a buffer or the name of one.")
506 (buffer)
507 register Lisp_Object buffer;
509 register Lisp_Object buf, tail, proc;
511 if (NILP (buffer)) return Qnil;
512 buf = Fget_buffer (buffer);
513 if (NILP (buf)) return Qnil;
515 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
517 proc = Fcdr (Fcar (tail));
518 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
519 return proc;
521 return Qnil;
524 /* This is how commands for the user decode process arguments. It
525 accepts a process, a process name, a buffer, a buffer name, or nil.
526 Buffers denote the first process in the buffer, and nil denotes the
527 current buffer. */
529 static Lisp_Object
530 get_process (name)
531 register Lisp_Object name;
533 register Lisp_Object proc, obj;
534 if (STRINGP (name))
536 obj = Fget_process (name);
537 if (NILP (obj))
538 obj = Fget_buffer (name);
539 if (NILP (obj))
540 error ("Process %s does not exist", XSTRING (name)->data);
542 else if (NILP (name))
543 obj = Fcurrent_buffer ();
544 else
545 obj = name;
547 /* Now obj should be either a buffer object or a process object.
549 if (BUFFERP (obj))
551 proc = Fget_buffer_process (obj);
552 if (NILP (proc))
553 error ("Buffer %s has no process", XSTRING (XBUFFER (obj)->name)->data);
555 else
557 CHECK_PROCESS (obj, 0);
558 proc = obj;
560 return proc;
563 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
564 "Delete PROCESS: kill it and forget about it immediately.\n\
565 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
566 nil, indicating the current buffer's process.")
567 (process)
568 register Lisp_Object process;
570 process = get_process (process);
571 XPROCESS (process)->raw_status_low = Qnil;
572 XPROCESS (process)->raw_status_high = Qnil;
573 if (NETCONN_P (process))
575 XPROCESS (process)->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
576 XSETINT (XPROCESS (process)->tick, ++process_tick);
578 else if (XINT (XPROCESS (process)->infd) >= 0)
580 Fkill_process (process, Qnil);
581 /* Do this now, since remove_process will make sigchld_handler do nothing. */
582 XPROCESS (process)->status
583 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
584 XSETINT (XPROCESS (process)->tick, ++process_tick);
585 status_notify ();
587 remove_process (process);
588 return Qnil;
591 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
592 "Return the status of PROCESS.\n\
593 The returned value is one of the following symbols:\n\
594 run -- for a process that is running.\n\
595 stop -- for a process stopped but continuable.\n\
596 exit -- for a process that has exited.\n\
597 signal -- for a process that has got a fatal signal.\n\
598 open -- for a network stream connection that is open.\n\
599 closed -- for a network stream connection that is closed.\n\
600 nil -- if arg is a process name and no such process exists.\n\
601 PROCESS may be a process, a buffer, the name of a process, or\n\
602 nil, indicating the current buffer's process.")
603 (process)
604 register Lisp_Object process;
606 register struct Lisp_Process *p;
607 register Lisp_Object status;
609 if (STRINGP (process))
610 process = Fget_process (process);
611 else
612 process = get_process (process);
614 if (NILP (process))
615 return process;
617 p = XPROCESS (process);
618 if (!NILP (p->raw_status_low))
619 update_status (p);
620 status = p->status;
621 if (CONSP (status))
622 status = XCAR (status);
623 if (NETCONN_P (process))
625 if (EQ (status, Qrun))
626 status = Qopen;
627 else if (EQ (status, Qexit))
628 status = Qclosed;
630 return status;
633 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
634 1, 1, 0,
635 "Return the exit status of PROCESS or the signal number that killed it.\n\
636 If PROCESS has not yet exited or died, return 0.")
637 (process)
638 register Lisp_Object process;
640 CHECK_PROCESS (process, 0);
641 if (!NILP (XPROCESS (process)->raw_status_low))
642 update_status (XPROCESS (process));
643 if (CONSP (XPROCESS (process)->status))
644 return XCAR (XCDR (XPROCESS (process)->status));
645 return make_number (0);
648 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
649 "Return the process id of PROCESS.\n\
650 This is the pid of the Unix process which PROCESS uses or talks to.\n\
651 For a network connection, this value is nil.")
652 (process)
653 register Lisp_Object process;
655 CHECK_PROCESS (process, 0);
656 return XPROCESS (process)->pid;
659 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
660 "Return the name of PROCESS, as a string.\n\
661 This is the name of the program invoked in PROCESS,\n\
662 possibly modified to make it unique among process names.")
663 (process)
664 register Lisp_Object process;
666 CHECK_PROCESS (process, 0);
667 return XPROCESS (process)->name;
670 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
671 "Return the command that was executed to start PROCESS.\n\
672 This is a list of strings, the first string being the program executed\n\
673 and the rest of the strings being the arguments given to it.\n\
674 For a non-child channel, this is nil.")
675 (process)
676 register Lisp_Object process;
678 CHECK_PROCESS (process, 0);
679 return XPROCESS (process)->command;
682 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
683 "Return the name of the terminal PROCESS uses, or nil if none.\n\
684 This is the terminal that the process itself reads and writes on,\n\
685 not the name of the pty that Emacs uses to talk with that terminal.")
686 (process)
687 register Lisp_Object process;
689 CHECK_PROCESS (process, 0);
690 return XPROCESS (process)->tty_name;
693 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
694 2, 2, 0,
695 "Set buffer associated with PROCESS to BUFFER (a buffer, or nil).")
696 (process, buffer)
697 register Lisp_Object process, buffer;
699 CHECK_PROCESS (process, 0);
700 if (!NILP (buffer))
701 CHECK_BUFFER (buffer, 1);
702 XPROCESS (process)->buffer = buffer;
703 return buffer;
706 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
707 1, 1, 0,
708 "Return the buffer PROCESS is associated with.\n\
709 Output from PROCESS is inserted in this buffer unless PROCESS has a filter.")
710 (process)
711 register Lisp_Object process;
713 CHECK_PROCESS (process, 0);
714 return XPROCESS (process)->buffer;
717 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
718 1, 1, 0,
719 "Return the marker for the end of the last output from PROCESS.")
720 (process)
721 register Lisp_Object process;
723 CHECK_PROCESS (process, 0);
724 return XPROCESS (process)->mark;
727 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
728 2, 2, 0,
729 "Give PROCESS the filter function FILTER; nil means no filter.\n\
730 t means stop accepting output from the process.\n\
731 When a process has a filter, each time it does output\n\
732 the entire string of output is passed to the filter.\n\
733 The filter gets two arguments: the process and the string of output.\n\
734 If the process has a filter, its buffer is not used for output.")
735 (process, filter)
736 register Lisp_Object process, filter;
738 CHECK_PROCESS (process, 0);
739 if (EQ (filter, Qt))
741 FD_CLR (XINT (XPROCESS (process)->infd), &input_wait_mask);
742 FD_CLR (XINT (XPROCESS (process)->infd), &non_keyboard_wait_mask);
744 else if (EQ (XPROCESS (process)->filter, Qt))
746 FD_SET (XINT (XPROCESS (process)->infd), &input_wait_mask);
747 FD_SET (XINT (XPROCESS (process)->infd), &non_keyboard_wait_mask);
749 XPROCESS (process)->filter = filter;
750 return filter;
753 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
754 1, 1, 0,
755 "Returns the filter function of PROCESS; nil if none.\n\
756 See `set-process-filter' for more info on filter functions.")
757 (process)
758 register Lisp_Object process;
760 CHECK_PROCESS (process, 0);
761 return XPROCESS (process)->filter;
764 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
765 2, 2, 0,
766 "Give PROCESS the sentinel SENTINEL; nil for none.\n\
767 The sentinel is called as a function when the process changes state.\n\
768 It gets two arguments: the process, and a string describing the change.")
769 (process, sentinel)
770 register Lisp_Object process, sentinel;
772 CHECK_PROCESS (process, 0);
773 XPROCESS (process)->sentinel = sentinel;
774 return sentinel;
777 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
778 1, 1, 0,
779 "Return the sentinel of PROCESS; nil if none.\n\
780 See `set-process-sentinel' for more info on sentinels.")
781 (process)
782 register Lisp_Object process;
784 CHECK_PROCESS (process, 0);
785 return XPROCESS (process)->sentinel;
788 DEFUN ("set-process-window-size", Fset_process_window_size,
789 Sset_process_window_size, 3, 3, 0,
790 "Tell PROCESS that it has logical window size HEIGHT and WIDTH.")
791 (process, height, width)
792 register Lisp_Object process, height, width;
794 CHECK_PROCESS (process, 0);
795 CHECK_NATNUM (height, 0);
796 CHECK_NATNUM (width, 0);
797 if (set_window_size (XINT (XPROCESS (process)->infd),
798 XINT (height), XINT (width)) <= 0)
799 return Qnil;
800 else
801 return Qt;
804 DEFUN ("set-process-inherit-coding-system-flag",
805 Fset_process_inherit_coding_system_flag,
806 Sset_process_inherit_coding_system_flag, 2, 2, 0,
807 "Determine whether buffer of PROCESS will inherit coding-system.\n\
808 If the second argument FLAG is non-nil, then the variable\n\
809 `buffer-file-coding-system' of the buffer associated with PROCESS\n\
810 will be bound to the value of the coding system used to decode\n\
811 the process output.\n\
813 This is useful when the coding system specified for the process buffer\n\
814 leaves either the character code conversion or the end-of-line conversion\n\
815 unspecified, or if the coding system used to decode the process output\n\
816 is more appropriate for saving the process buffer.\n\
818 Binding the variable `inherit-process-coding-system' to non-nil before\n\
819 starting the process is an alternative way of setting the inherit flag\n\
820 for the process which will run.")
821 (process, flag)
822 register Lisp_Object process, flag;
824 CHECK_PROCESS (process, 0);
825 XPROCESS (process)->inherit_coding_system_flag = flag;
826 return flag;
829 DEFUN ("process-inherit-coding-system-flag",
830 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
831 1, 1, 0,
832 "Return the value of inherit-coding-system flag for PROCESS.\n\
833 If this flag is t, `buffer-file-coding-system' of the buffer\n\
834 associated with PROCESS will inherit the coding system used to decode\n\
835 the process output.")
836 (process)
837 register Lisp_Object process;
839 CHECK_PROCESS (process, 0);
840 return XPROCESS (process)->inherit_coding_system_flag;
843 DEFUN ("process-kill-without-query", Fprocess_kill_without_query,
844 Sprocess_kill_without_query, 1, 2, 0,
845 "Say no query needed if PROCESS is running when Emacs is exited.\n\
846 Optional second argument if non-nil says to require a query.\n\
847 Value is t if a query was formerly required.")
848 (process, value)
849 register Lisp_Object process, value;
851 Lisp_Object tem;
853 CHECK_PROCESS (process, 0);
854 tem = XPROCESS (process)->kill_without_query;
855 XPROCESS (process)->kill_without_query = Fnull (value);
857 return Fnull (tem);
860 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
861 1, 1, 0,
862 "Return the contact info of PROCESS; t for a real child.\n\
863 For a net connection, the value is a cons cell of the form (HOST SERVICE).")
864 (process)
865 register Lisp_Object process;
867 CHECK_PROCESS (process, 0);
868 return XPROCESS (process)->childp;
871 #if 0 /* Turned off because we don't currently record this info
872 in the process. Perhaps add it. */
873 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
874 "Return the connection type of PROCESS.\n\
875 The value is nil for a pipe, t or `pty' for a pty, or `stream' for\n\
876 a socket connection.")
877 (process)
878 Lisp_Object process;
880 return XPROCESS (process)->type;
882 #endif
884 Lisp_Object
885 list_processes_1 ()
887 register Lisp_Object tail, tem;
888 Lisp_Object proc, minspace, tem1;
889 register struct Lisp_Process *p;
890 char tembuf[80];
892 XSETFASTINT (minspace, 1);
894 set_buffer_internal (XBUFFER (Vstandard_output));
895 Fbuffer_disable_undo (Vstandard_output);
897 current_buffer->truncate_lines = Qt;
899 write_string ("\
900 Proc Status Buffer Tty Command\n\
901 ---- ------ ------ --- -------\n", -1);
903 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
905 Lisp_Object symbol;
907 proc = Fcdr (Fcar (tail));
908 p = XPROCESS (proc);
909 if (NILP (p->childp))
910 continue;
912 Finsert (1, &p->name);
913 Findent_to (make_number (13), minspace);
915 if (!NILP (p->raw_status_low))
916 update_status (p);
917 symbol = p->status;
918 if (CONSP (p->status))
919 symbol = XCAR (p->status);
922 if (EQ (symbol, Qsignal))
924 Lisp_Object tem;
925 tem = Fcar (Fcdr (p->status));
926 #ifdef VMS
927 if (XINT (tem) < NSIG)
928 write_string (sys_errlist [XINT (tem)], -1);
929 else
930 #endif
931 Fprinc (symbol, Qnil);
933 else if (NETCONN_P (proc))
935 if (EQ (symbol, Qrun))
936 write_string ("open", -1);
937 else if (EQ (symbol, Qexit))
938 write_string ("closed", -1);
939 else
940 Fprinc (symbol, Qnil);
942 else
943 Fprinc (symbol, Qnil);
945 if (EQ (symbol, Qexit))
947 Lisp_Object tem;
948 tem = Fcar (Fcdr (p->status));
949 if (XFASTINT (tem))
951 sprintf (tembuf, " %d", (int) XFASTINT (tem));
952 write_string (tembuf, -1);
956 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
957 remove_process (proc);
959 Findent_to (make_number (22), minspace);
960 if (NILP (p->buffer))
961 insert_string ("(none)");
962 else if (NILP (XBUFFER (p->buffer)->name))
963 insert_string ("(Killed)");
964 else
965 Finsert (1, &XBUFFER (p->buffer)->name);
967 Findent_to (make_number (37), minspace);
969 if (STRINGP (p->tty_name))
970 Finsert (1, &p->tty_name);
971 else
972 insert_string ("(none)");
974 Findent_to (make_number (49), minspace);
976 if (NETCONN_P (proc))
978 sprintf (tembuf, "(network stream connection to %s)\n",
979 XSTRING (XCAR (p->childp))->data);
980 insert_string (tembuf);
982 else
984 tem = p->command;
985 while (1)
987 tem1 = Fcar (tem);
988 Finsert (1, &tem1);
989 tem = Fcdr (tem);
990 if (NILP (tem))
991 break;
992 insert_string (" ");
994 insert_string ("\n");
997 return Qnil;
1000 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 0, "",
1001 "Display a list of all processes.\n\
1002 Any process listed as exited or signaled is actually eliminated\n\
1003 after the listing is made.")
1006 internal_with_output_to_temp_buffer ("*Process List*",
1007 list_processes_1, Qnil);
1008 return Qnil;
1011 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1012 "Return a list of all processes.")
1015 return Fmapcar (Qcdr, Vprocess_alist);
1018 /* Starting asynchronous inferior processes. */
1020 static Lisp_Object start_process_unwind ();
1022 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1023 "Start a program in a subprocess. Return the process object for it.\n\
1024 Args are NAME BUFFER PROGRAM &rest PROGRAM-ARGS\n\
1025 NAME is name for process. It is modified if necessary to make it unique.\n\
1026 BUFFER is the buffer or (buffer-name) to associate with the process.\n\
1027 Process output goes at end of that buffer, unless you specify\n\
1028 an output stream or filter function to handle the output.\n\
1029 BUFFER may be also nil, meaning that this process is not associated\n\
1030 with any buffer.\n\
1031 Third arg is program file name. It is searched for in PATH.\n\
1032 Remaining arguments are strings to give program as arguments.")
1033 (nargs, args)
1034 int nargs;
1035 register Lisp_Object *args;
1037 Lisp_Object buffer, name, program, proc, current_dir, tem;
1038 #ifdef VMS
1039 register unsigned char *new_argv;
1040 int len;
1041 #else
1042 register unsigned char **new_argv;
1043 #endif
1044 register int i;
1045 int count = specpdl_ptr - specpdl;
1047 buffer = args[1];
1048 if (!NILP (buffer))
1049 buffer = Fget_buffer_create (buffer);
1051 /* Make sure that the child will be able to chdir to the current
1052 buffer's current directory, or its unhandled equivalent. We
1053 can't just have the child check for an error when it does the
1054 chdir, since it's in a vfork.
1056 We have to GCPRO around this because Fexpand_file_name and
1057 Funhandled_file_name_directory might call a file name handling
1058 function. The argument list is protected by the caller, so all
1059 we really have to worry about is buffer. */
1061 struct gcpro gcpro1, gcpro2;
1063 current_dir = current_buffer->directory;
1065 GCPRO2 (buffer, current_dir);
1067 current_dir
1068 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
1069 Qnil);
1070 if (NILP (Ffile_accessible_directory_p (current_dir)))
1071 report_file_error ("Setting current directory",
1072 Fcons (current_buffer->directory, Qnil));
1074 UNGCPRO;
1077 name = args[0];
1078 CHECK_STRING (name, 0);
1080 program = args[2];
1082 CHECK_STRING (program, 2);
1084 #ifdef VMS
1085 /* Make a one member argv with all args concatenated
1086 together separated by a blank. */
1087 len = STRING_BYTES (XSTRING (program)) + 2;
1088 for (i = 3; i < nargs; i++)
1090 tem = args[i];
1091 CHECK_STRING (tem, i);
1092 len += STRING_BYTES (XSTRING (tem)) + 1; /* count the blank */
1094 new_argv = (unsigned char *) alloca (len);
1095 strcpy (new_argv, XSTRING (program)->data);
1096 for (i = 3; i < nargs; i++)
1098 tem = args[i];
1099 CHECK_STRING (tem, i);
1100 strcat (new_argv, " ");
1101 strcat (new_argv, XSTRING (tem)->data);
1103 /* Need to add code here to check for program existence on VMS */
1105 #else /* not VMS */
1106 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1108 /* If program file name is not absolute, search our path for it */
1109 if (!IS_DIRECTORY_SEP (XSTRING (program)->data[0])
1110 && !(XSTRING (program)->size > 1
1111 && IS_DEVICE_SEP (XSTRING (program)->data[1])))
1113 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1115 tem = Qnil;
1116 GCPRO4 (name, program, buffer, current_dir);
1117 openp (Vexec_path, program, EXEC_SUFFIXES, &tem, 1);
1118 UNGCPRO;
1119 if (NILP (tem))
1120 report_file_error ("Searching for program", Fcons (program, Qnil));
1121 tem = Fexpand_file_name (tem, Qnil);
1122 new_argv[0] = XSTRING (tem)->data;
1124 else
1126 if (!NILP (Ffile_directory_p (program)))
1127 error ("Specified program for new process is a directory");
1129 new_argv[0] = XSTRING (program)->data;
1132 for (i = 3; i < nargs; i++)
1134 tem = args[i];
1135 CHECK_STRING (tem, i);
1136 new_argv[i - 2] = XSTRING (tem)->data;
1138 new_argv[i - 2] = 0;
1139 #endif /* not VMS */
1141 proc = make_process (name);
1142 /* If an error occurs and we can't start the process, we want to
1143 remove it from the process list. This means that each error
1144 check in create_process doesn't need to call remove_process
1145 itself; it's all taken care of here. */
1146 record_unwind_protect (start_process_unwind, proc);
1148 XPROCESS (proc)->childp = Qt;
1149 XPROCESS (proc)->command_channel_p = Qnil;
1150 XPROCESS (proc)->buffer = buffer;
1151 XPROCESS (proc)->sentinel = Qnil;
1152 XPROCESS (proc)->filter = Qnil;
1153 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1155 /* Make the process marker point into the process buffer (if any). */
1156 if (!NILP (buffer))
1157 set_marker_both (XPROCESS (proc)->mark, buffer,
1158 BUF_ZV (XBUFFER (buffer)),
1159 BUF_ZV_BYTE (XBUFFER (buffer)));
1162 /* Decide coding systems for communicating with the process. Here
1163 we don't setup the structure coding_system nor pay attention to
1164 unibyte mode. They are done in create_process. */
1166 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1167 Lisp_Object coding_systems = Qt;
1168 Lisp_Object val, *args2;
1169 struct gcpro gcpro1;
1171 val = Vcoding_system_for_read;
1172 if (NILP (val))
1174 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1175 args2[0] = Qstart_process;
1176 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1177 GCPRO1 (proc);
1178 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1179 UNGCPRO;
1180 if (CONSP (coding_systems))
1181 val = XCAR (coding_systems);
1182 else if (CONSP (Vdefault_process_coding_system))
1183 val = XCAR (Vdefault_process_coding_system);
1185 XPROCESS (proc)->decode_coding_system = val;
1187 val = Vcoding_system_for_write;
1188 if (NILP (val))
1190 if (EQ (coding_systems, Qt))
1192 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1193 args2[0] = Qstart_process;
1194 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1195 GCPRO1 (proc);
1196 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1197 UNGCPRO;
1199 if (CONSP (coding_systems))
1200 val = XCDR (coding_systems);
1201 else if (CONSP (Vdefault_process_coding_system))
1202 val = XCDR (Vdefault_process_coding_system);
1204 XPROCESS (proc)->encode_coding_system = val;
1207 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1208 XPROCESS (proc)->decoding_carryover = make_number (0);
1209 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1210 XPROCESS (proc)->encoding_carryover = make_number (0);
1212 XPROCESS (proc)->inherit_coding_system_flag
1213 = (NILP (buffer) || !inherit_process_coding_system
1214 ? Qnil : Qt);
1216 create_process (proc, (char **) new_argv, current_dir);
1218 return unbind_to (count, proc);
1221 /* This function is the unwind_protect form for Fstart_process. If
1222 PROC doesn't have its pid set, then we know someone has signaled
1223 an error and the process wasn't started successfully, so we should
1224 remove it from the process list. */
1225 static Lisp_Object
1226 start_process_unwind (proc)
1227 Lisp_Object proc;
1229 if (!PROCESSP (proc))
1230 abort ();
1232 /* Was PROC started successfully? */
1233 if (XINT (XPROCESS (proc)->pid) <= 0)
1234 remove_process (proc);
1236 return Qnil;
1240 SIGTYPE
1241 create_process_1 (signo)
1242 int signo;
1244 #if defined (USG) && !defined (POSIX_SIGNALS)
1245 /* USG systems forget handlers when they are used;
1246 must reestablish each time */
1247 signal (signo, create_process_1);
1248 #endif /* USG */
1251 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1252 #ifdef USG
1253 #ifdef SIGCHLD
1254 /* Mimic blocking of signals on system V, which doesn't really have it. */
1256 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1257 int sigchld_deferred;
1259 SIGTYPE
1260 create_process_sigchld ()
1262 signal (SIGCHLD, create_process_sigchld);
1264 sigchld_deferred = 1;
1266 #endif
1267 #endif
1268 #endif
1270 #ifndef VMS /* VMS version of this function is in vmsproc.c. */
1271 void
1272 create_process (process, new_argv, current_dir)
1273 Lisp_Object process;
1274 char **new_argv;
1275 Lisp_Object current_dir;
1277 int pid, inchannel, outchannel;
1278 int sv[2];
1279 #ifdef POSIX_SIGNALS
1280 sigset_t procmask;
1281 sigset_t blocked;
1282 struct sigaction sigint_action;
1283 struct sigaction sigquit_action;
1284 #ifdef AIX
1285 struct sigaction sighup_action;
1286 #endif
1287 #else /* !POSIX_SIGNALS */
1288 #if 0
1289 #ifdef SIGCHLD
1290 SIGTYPE (*sigchld)();
1291 #endif
1292 #endif /* 0 */
1293 #endif /* !POSIX_SIGNALS */
1294 /* Use volatile to protect variables from being clobbered by longjmp. */
1295 volatile int forkin, forkout;
1296 volatile int pty_flag = 0;
1297 extern char **environ;
1298 Lisp_Object buffer = XPROCESS (process)->buffer;
1300 inchannel = outchannel = -1;
1302 #ifdef HAVE_PTYS
1303 if (!NILP (Vprocess_connection_type))
1304 outchannel = inchannel = allocate_pty ();
1306 if (inchannel >= 0)
1308 #ifndef USG
1309 /* On USG systems it does not work to open the pty's tty here
1310 and then close and reopen it in the child. */
1311 #ifdef O_NOCTTY
1312 /* Don't let this terminal become our controlling terminal
1313 (in case we don't have one). */
1314 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1315 #else
1316 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1317 #endif
1318 if (forkin < 0)
1319 report_file_error ("Opening pty", Qnil);
1320 #else
1321 forkin = forkout = -1;
1322 #endif /* not USG */
1323 pty_flag = 1;
1325 else
1326 #endif /* HAVE_PTYS */
1327 #ifdef SKTPAIR
1329 if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
1330 report_file_error ("Opening socketpair", Qnil);
1331 outchannel = inchannel = sv[0];
1332 forkout = forkin = sv[1];
1334 #else /* not SKTPAIR */
1336 int tem;
1337 tem = pipe (sv);
1338 if (tem < 0)
1339 report_file_error ("Creating pipe", Qnil);
1340 inchannel = sv[0];
1341 forkout = sv[1];
1342 tem = pipe (sv);
1343 if (tem < 0)
1345 emacs_close (inchannel);
1346 emacs_close (forkout);
1347 report_file_error ("Creating pipe", Qnil);
1349 outchannel = sv[1];
1350 forkin = sv[0];
1352 #endif /* not SKTPAIR */
1354 #if 0
1355 /* Replaced by close_process_descs */
1356 set_exclusive_use (inchannel);
1357 set_exclusive_use (outchannel);
1358 #endif
1360 /* Stride people say it's a mystery why this is needed
1361 as well as the O_NDELAY, but that it fails without this. */
1362 #if defined (STRIDE) || (defined (pfa) && defined (HAVE_PTYS))
1364 int one = 1;
1365 ioctl (inchannel, FIONBIO, &one);
1367 #endif
1369 #ifdef O_NONBLOCK
1370 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1371 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1372 #else
1373 #ifdef O_NDELAY
1374 fcntl (inchannel, F_SETFL, O_NDELAY);
1375 fcntl (outchannel, F_SETFL, O_NDELAY);
1376 #endif
1377 #endif
1379 /* Record this as an active process, with its channels.
1380 As a result, child_setup will close Emacs's side of the pipes. */
1381 chan_process[inchannel] = process;
1382 XSETINT (XPROCESS (process)->infd, inchannel);
1383 XSETINT (XPROCESS (process)->outfd, outchannel);
1384 /* Record the tty descriptor used in the subprocess. */
1385 if (forkin < 0)
1386 XPROCESS (process)->subtty = Qnil;
1387 else
1388 XSETFASTINT (XPROCESS (process)->subtty, forkin);
1389 XPROCESS (process)->pty_flag = (pty_flag ? Qt : Qnil);
1390 XPROCESS (process)->status = Qrun;
1391 if (!proc_decode_coding_system[inchannel])
1392 proc_decode_coding_system[inchannel]
1393 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
1394 setup_coding_system (XPROCESS (process)->decode_coding_system,
1395 proc_decode_coding_system[inchannel]);
1396 if (!proc_encode_coding_system[outchannel])
1397 proc_encode_coding_system[outchannel]
1398 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
1399 setup_coding_system (XPROCESS (process)->encode_coding_system,
1400 proc_encode_coding_system[outchannel]);
1402 if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
1403 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
1405 /* In unibyte mode, character code conversion should not take
1406 place but EOL conversion should. So, setup raw-text or one
1407 of the subsidiary according to the information just setup. */
1408 if (!NILP (XPROCESS (process)->decode_coding_system))
1409 setup_raw_text_coding_system (proc_decode_coding_system[inchannel]);
1410 if (!NILP (XPROCESS (process)->encode_coding_system))
1411 setup_raw_text_coding_system (proc_encode_coding_system[outchannel]);
1414 if (CODING_REQUIRE_ENCODING (proc_encode_coding_system[outchannel]))
1416 /* Here we encode arguments by the coding system used for
1417 sending data to the process. We don't support using
1418 different coding systems for encoding arguments and for
1419 encoding data sent to the process. */
1420 struct gcpro gcpro1;
1421 int i = 1;
1422 struct coding_system *coding = proc_encode_coding_system[outchannel];
1424 coding->mode |= CODING_MODE_LAST_BLOCK;
1425 GCPRO1 (process);
1426 while (new_argv[i] != 0)
1428 int len = strlen (new_argv[i]);
1429 int size = encoding_buffer_size (coding, len);
1430 unsigned char *buf = (unsigned char *) alloca (size);
1432 encode_coding (coding, (unsigned char *)new_argv[i], buf, len, size);
1433 buf[coding->produced] = 0;
1434 /* We don't have to free new_argv[i] because it points to a
1435 Lisp string given as an argument to `start-process'. */
1436 new_argv[i++] = (char *) buf;
1438 UNGCPRO;
1439 coding->mode &= ~CODING_MODE_LAST_BLOCK;
1442 /* Delay interrupts until we have a chance to store
1443 the new fork's pid in its process structure */
1444 #ifdef POSIX_SIGNALS
1445 sigemptyset (&blocked);
1446 #ifdef SIGCHLD
1447 sigaddset (&blocked, SIGCHLD);
1448 #endif
1449 #ifdef HAVE_VFORK
1450 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1451 this sets the parent's signal handlers as well as the child's.
1452 So delay all interrupts whose handlers the child might munge,
1453 and record the current handlers so they can be restored later. */
1454 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1455 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1456 #ifdef AIX
1457 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1458 #endif
1459 #endif /* HAVE_VFORK */
1460 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1461 #else /* !POSIX_SIGNALS */
1462 #ifdef SIGCHLD
1463 #ifdef BSD4_1
1464 sighold (SIGCHLD);
1465 #else /* not BSD4_1 */
1466 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1467 sigsetmask (sigmask (SIGCHLD));
1468 #else /* ordinary USG */
1469 #if 0
1470 sigchld_deferred = 0;
1471 sigchld = signal (SIGCHLD, create_process_sigchld);
1472 #endif
1473 #endif /* ordinary USG */
1474 #endif /* not BSD4_1 */
1475 #endif /* SIGCHLD */
1476 #endif /* !POSIX_SIGNALS */
1478 FD_SET (inchannel, &input_wait_mask);
1479 FD_SET (inchannel, &non_keyboard_wait_mask);
1480 if (inchannel > max_process_desc)
1481 max_process_desc = inchannel;
1483 /* Until we store the proper pid, enable sigchld_handler
1484 to recognize an unknown pid as standing for this process.
1485 It is very important not to let this `marker' value stay
1486 in the table after this function has returned; if it does
1487 it might cause call-process to hang and subsequent asynchronous
1488 processes to get their return values scrambled. */
1489 XSETINT (XPROCESS (process)->pid, -1);
1491 BLOCK_INPUT;
1494 /* child_setup must clobber environ on systems with true vfork.
1495 Protect it from permanent change. */
1496 char **save_environ = environ;
1498 current_dir = ENCODE_FILE (current_dir);
1500 #ifndef WINDOWSNT
1501 pid = vfork ();
1502 if (pid == 0)
1503 #endif /* not WINDOWSNT */
1505 int xforkin = forkin;
1506 int xforkout = forkout;
1508 #if 0 /* This was probably a mistake--it duplicates code later on,
1509 but fails to handle all the cases. */
1510 /* Make sure SIGCHLD is not blocked in the child. */
1511 sigsetmask (SIGEMPTYMASK);
1512 #endif
1514 /* Make the pty be the controlling terminal of the process. */
1515 #ifdef HAVE_PTYS
1516 /* First, disconnect its current controlling terminal. */
1517 #ifdef HAVE_SETSID
1518 /* We tried doing setsid only if pty_flag, but it caused
1519 process_set_signal to fail on SGI when using a pipe. */
1520 setsid ();
1521 /* Make the pty's terminal the controlling terminal. */
1522 if (pty_flag)
1524 #ifdef TIOCSCTTY
1525 /* We ignore the return value
1526 because faith@cs.unc.edu says that is necessary on Linux. */
1527 ioctl (xforkin, TIOCSCTTY, 0);
1528 #endif
1530 #else /* not HAVE_SETSID */
1531 #ifdef USG
1532 /* It's very important to call setpgrp here and no time
1533 afterwards. Otherwise, we lose our controlling tty which
1534 is set when we open the pty. */
1535 setpgrp ();
1536 #endif /* USG */
1537 #endif /* not HAVE_SETSID */
1538 #if defined (HAVE_TERMIOS) && defined (LDISC1)
1539 if (pty_flag && xforkin >= 0)
1541 struct termios t;
1542 tcgetattr (xforkin, &t);
1543 t.c_lflag = LDISC1;
1544 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1545 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1547 #else
1548 #if defined (NTTYDISC) && defined (TIOCSETD)
1549 if (pty_flag && xforkin >= 0)
1551 /* Use new line discipline. */
1552 int ldisc = NTTYDISC;
1553 ioctl (xforkin, TIOCSETD, &ldisc);
1555 #endif
1556 #endif
1557 #ifdef TIOCNOTTY
1558 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1559 can do TIOCSPGRP only to the process's controlling tty. */
1560 if (pty_flag)
1562 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1563 I can't test it since I don't have 4.3. */
1564 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1565 ioctl (j, TIOCNOTTY, 0);
1566 emacs_close (j);
1567 #ifndef USG
1568 /* In order to get a controlling terminal on some versions
1569 of BSD, it is necessary to put the process in pgrp 0
1570 before it opens the terminal. */
1571 #ifdef HAVE_SETPGID
1572 setpgid (0, 0);
1573 #else
1574 setpgrp (0, 0);
1575 #endif
1576 #endif
1578 #endif /* TIOCNOTTY */
1580 #if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
1581 /*** There is a suggestion that this ought to be a
1582 conditional on TIOCSPGRP,
1583 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1584 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1585 that system does seem to need this code, even though
1586 both HAVE_SETSID and TIOCSCTTY are defined. */
1587 /* Now close the pty (if we had it open) and reopen it.
1588 This makes the pty the controlling terminal of the subprocess. */
1589 if (pty_flag)
1591 #ifdef SET_CHILD_PTY_PGRP
1592 int pgrp = getpid ();
1593 #endif
1595 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1596 would work? */
1597 if (xforkin >= 0)
1598 emacs_close (xforkin);
1599 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1601 if (xforkin < 0)
1603 emacs_write (1, "Couldn't open the pty terminal ", 31);
1604 emacs_write (1, pty_name, strlen (pty_name));
1605 emacs_write (1, "\n", 1);
1606 _exit (1);
1609 #ifdef SET_CHILD_PTY_PGRP
1610 ioctl (xforkin, TIOCSPGRP, &pgrp);
1611 ioctl (xforkout, TIOCSPGRP, &pgrp);
1612 #endif
1614 #endif /* not UNIPLUS and not RTU and not DONT_REOPEN_PTY */
1616 #ifdef SETUP_SLAVE_PTY
1617 if (pty_flag)
1619 SETUP_SLAVE_PTY;
1621 #endif /* SETUP_SLAVE_PTY */
1622 #ifdef AIX
1623 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1624 Now reenable it in the child, so it will die when we want it to. */
1625 if (pty_flag)
1626 signal (SIGHUP, SIG_DFL);
1627 #endif
1628 #endif /* HAVE_PTYS */
1630 signal (SIGINT, SIG_DFL);
1631 signal (SIGQUIT, SIG_DFL);
1633 /* Stop blocking signals in the child. */
1634 #ifdef POSIX_SIGNALS
1635 sigprocmask (SIG_SETMASK, &procmask, 0);
1636 #else /* !POSIX_SIGNALS */
1637 #ifdef SIGCHLD
1638 #ifdef BSD4_1
1639 sigrelse (SIGCHLD);
1640 #else /* not BSD4_1 */
1641 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1642 sigsetmask (SIGEMPTYMASK);
1643 #else /* ordinary USG */
1644 #if 0
1645 signal (SIGCHLD, sigchld);
1646 #endif
1647 #endif /* ordinary USG */
1648 #endif /* not BSD4_1 */
1649 #endif /* SIGCHLD */
1650 #endif /* !POSIX_SIGNALS */
1652 if (pty_flag)
1653 child_setup_tty (xforkout);
1654 #ifdef WINDOWSNT
1655 pid = child_setup (xforkin, xforkout, xforkout,
1656 new_argv, 1, current_dir);
1657 #else /* not WINDOWSNT */
1658 child_setup (xforkin, xforkout, xforkout,
1659 new_argv, 1, current_dir);
1660 #endif /* not WINDOWSNT */
1662 environ = save_environ;
1665 UNBLOCK_INPUT;
1667 /* This runs in the Emacs process. */
1668 if (pid < 0)
1670 if (forkin >= 0)
1671 emacs_close (forkin);
1672 if (forkin != forkout && forkout >= 0)
1673 emacs_close (forkout);
1675 else
1677 /* vfork succeeded. */
1678 XSETFASTINT (XPROCESS (process)->pid, pid);
1680 #ifdef WINDOWSNT
1681 register_child (pid, inchannel);
1682 #endif /* WINDOWSNT */
1684 /* If the subfork execv fails, and it exits,
1685 this close hangs. I don't know why.
1686 So have an interrupt jar it loose. */
1687 stop_polling ();
1688 signal (SIGALRM, create_process_1);
1689 alarm (1);
1690 XPROCESS (process)->subtty = Qnil;
1691 if (forkin >= 0)
1692 emacs_close (forkin);
1693 alarm (0);
1694 start_polling ();
1695 if (forkin != forkout && forkout >= 0)
1696 emacs_close (forkout);
1698 #ifdef HAVE_PTYS
1699 if (pty_flag)
1700 XPROCESS (process)->tty_name = build_string (pty_name);
1701 else
1702 #endif
1703 XPROCESS (process)->tty_name = Qnil;
1706 /* Restore the signal state whether vfork succeeded or not.
1707 (We will signal an error, below, if it failed.) */
1708 #ifdef POSIX_SIGNALS
1709 #ifdef HAVE_VFORK
1710 /* Restore the parent's signal handlers. */
1711 sigaction (SIGINT, &sigint_action, 0);
1712 sigaction (SIGQUIT, &sigquit_action, 0);
1713 #ifdef AIX
1714 sigaction (SIGHUP, &sighup_action, 0);
1715 #endif
1716 #endif /* HAVE_VFORK */
1717 /* Stop blocking signals in the parent. */
1718 sigprocmask (SIG_SETMASK, &procmask, 0);
1719 #else /* !POSIX_SIGNALS */
1720 #ifdef SIGCHLD
1721 #ifdef BSD4_1
1722 sigrelse (SIGCHLD);
1723 #else /* not BSD4_1 */
1724 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1725 sigsetmask (SIGEMPTYMASK);
1726 #else /* ordinary USG */
1727 #if 0
1728 signal (SIGCHLD, sigchld);
1729 /* Now really handle any of these signals
1730 that came in during this function. */
1731 if (sigchld_deferred)
1732 kill (getpid (), SIGCHLD);
1733 #endif
1734 #endif /* ordinary USG */
1735 #endif /* not BSD4_1 */
1736 #endif /* SIGCHLD */
1737 #endif /* !POSIX_SIGNALS */
1739 /* Now generate the error if vfork failed. */
1740 if (pid < 0)
1741 report_file_error ("Doing vfork", Qnil);
1743 #endif /* not VMS */
1745 #ifdef HAVE_SOCKETS
1747 /* open a TCP network connection to a given HOST/SERVICE. Treated
1748 exactly like a normal process when reading and writing. Only
1749 differences are in status display and process deletion. A network
1750 connection has no PID; you cannot signal it. All you can do is
1751 deactivate and close it via delete-process */
1753 DEFUN ("open-network-stream", Fopen_network_stream, Sopen_network_stream,
1754 4, 4, 0,
1755 "Open a TCP connection for a service to a host.\n\
1756 Returns a subprocess-object to represent the connection.\n\
1757 Input and output work as for subprocesses; `delete-process' closes it.\n\
1758 Args are NAME BUFFER HOST SERVICE.\n\
1759 NAME is name for process. It is modified if necessary to make it unique.\n\
1760 BUFFER is the buffer (or buffer-name) to associate with the process.\n\
1761 Process output goes at end of that buffer, unless you specify\n\
1762 an output stream or filter function to handle the output.\n\
1763 BUFFER may be also nil, meaning that this process is not associated\n\
1764 with any buffer\n\
1765 Third arg is name of the host to connect to, or its IP address.\n\
1766 Fourth arg SERVICE is name of the service desired, or an integer\n\
1767 specifying a port number to connect to.")
1768 (name, buffer, host, service)
1769 Lisp_Object name, buffer, host, service;
1771 Lisp_Object proc;
1772 #ifndef HAVE_GETADDRINFO
1773 struct sockaddr_in address;
1774 struct servent *svc_info;
1775 struct hostent *host_info_ptr, host_info;
1776 char *(addr_list[2]);
1777 IN_ADDR numeric_addr;
1778 int port;
1779 #else /* HAVE_GETADDRINFO */
1780 struct addrinfo hints, *res, *lres;
1781 int ret = 0;
1782 int xerrno = 0;
1783 char *portstring, portbuf[128];
1784 #endif /* HAVE_GETADDRINFO */
1785 int s = -1, outch, inch;
1786 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1787 int retry = 0;
1788 int count = specpdl_ptr - specpdl;
1789 int count1;
1791 #ifdef WINDOWSNT
1792 /* Ensure socket support is loaded if available. */
1793 init_winsock (TRUE);
1794 #endif
1796 GCPRO4 (name, buffer, host, service);
1797 CHECK_STRING (name, 0);
1798 CHECK_STRING (host, 0);
1800 #ifdef HAVE_GETADDRINFO
1802 * SERVICE can either be a string or int.
1803 * Convert to a C string for later use by getaddrinfo.
1805 if (INTEGERP (service))
1807 sprintf (portbuf, "%d", XINT (service));
1808 portstring = portbuf;
1810 else
1812 CHECK_STRING (service, 0);
1813 portstring = XSTRING (service)->data;
1815 #else /* ! HAVE_GETADDRINFO */
1816 if (INTEGERP (service))
1817 port = htons ((unsigned short) XINT (service));
1818 else
1820 CHECK_STRING (service, 0);
1821 svc_info = getservbyname (XSTRING (service)->data, "tcp");
1822 if (svc_info == 0)
1823 error ("Unknown service \"%s\"", XSTRING (service)->data);
1824 port = svc_info->s_port;
1826 #endif /* ! HAVE_GETADDRINFO */
1829 /* Slow down polling to every ten seconds.
1830 Some kernels have a bug which causes retrying connect to fail
1831 after a connect. Polling can interfere with gethostbyname too. */
1832 #ifdef POLL_FOR_INPUT
1833 bind_polling_period (10);
1834 #endif
1836 #ifndef TERM
1837 #ifdef HAVE_GETADDRINFO
1839 immediate_quit = 1;
1840 QUIT;
1841 memset (&hints, 0, sizeof (hints));
1842 hints.ai_flags = 0;
1843 hints.ai_family = AF_UNSPEC;
1844 hints.ai_socktype = SOCK_STREAM;
1845 hints.ai_protocol = 0;
1846 ret = getaddrinfo (XSTRING (host)->data, portstring, &hints, &res);
1847 if (ret)
1849 error ("%s/%s %s", XSTRING (host)->data, portstring,
1850 strerror (ret));
1852 immediate_quit = 0;
1855 s = -1;
1856 count1 = specpdl_ptr - specpdl;
1857 record_unwind_protect (close_file_unwind, make_number (s));
1859 for (lres = res; lres; lres = lres->ai_next)
1861 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
1862 if (s < 0)
1863 continue;
1865 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1866 when connect is interrupted. So let's not let it get interrupted.
1867 Note we do not turn off polling, because polling is only used
1868 when not interrupt_input, and thus not normally used on the systems
1869 which have this bug. On systems which use polling, there's no way
1870 to quit if polling is turned off. */
1871 if (interrupt_input)
1872 unrequest_sigio ();
1874 immediate_quit = 1;
1875 QUIT;
1877 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
1878 if (ret == 0)
1879 break;
1880 emacs_close (s);
1881 s = -1;
1884 freeaddrinfo (res);
1885 if (s < 0)
1887 if (interrupt_input)
1888 request_sigio ();
1890 errno = xerrno;
1891 report_file_error ("connection failed",
1892 Fcons (host, Fcons (name, Qnil)));
1894 #else /* ! HAVE_GETADDRINFO */
1896 while (1)
1898 #if 0
1899 #ifdef TRY_AGAIN
1900 h_errno = 0;
1901 #endif
1902 #endif
1903 immediate_quit = 1;
1904 QUIT;
1905 host_info_ptr = gethostbyname (XSTRING (host)->data);
1906 immediate_quit = 0;
1907 #if 0
1908 #ifdef TRY_AGAIN
1909 if (! (host_info_ptr == 0 && h_errno == TRY_AGAIN))
1910 #endif
1911 #endif
1912 break;
1913 Fsleep_for (make_number (1), Qnil);
1915 if (host_info_ptr == 0)
1916 /* Attempt to interpret host as numeric inet address */
1918 numeric_addr = inet_addr ((char *) XSTRING (host)->data);
1919 if (NUMERIC_ADDR_ERROR)
1920 error ("Unknown host \"%s\"", XSTRING (host)->data);
1922 host_info_ptr = &host_info;
1923 host_info.h_name = 0;
1924 host_info.h_aliases = 0;
1925 host_info.h_addrtype = AF_INET;
1926 #ifdef h_addr
1927 /* Older machines have only one address slot called h_addr.
1928 Newer machines have h_addr_list, but #define h_addr to
1929 be its first element. */
1930 host_info.h_addr_list = &(addr_list[0]);
1931 #endif
1932 host_info.h_addr = (char*)(&numeric_addr);
1933 addr_list[1] = 0;
1934 /* numeric_addr isn't null-terminated; it has fixed length. */
1935 host_info.h_length = sizeof (numeric_addr);
1938 bzero (&address, sizeof address);
1939 bcopy (host_info_ptr->h_addr, (char *) &address.sin_addr,
1940 host_info_ptr->h_length);
1941 address.sin_family = host_info_ptr->h_addrtype;
1942 address.sin_port = port;
1944 s = socket (host_info_ptr->h_addrtype, SOCK_STREAM, 0);
1945 if (s < 0)
1946 report_file_error ("error creating socket", Fcons (name, Qnil));
1948 count1 = specpdl_ptr - specpdl;
1949 record_unwind_protect (close_file_unwind, make_number (s));
1951 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
1952 when connect is interrupted. So let's not let it get interrupted.
1953 Note we do not turn off polling, because polling is only used
1954 when not interrupt_input, and thus not normally used on the systems
1955 which have this bug. On systems which use polling, there's no way
1956 to quit if polling is turned off. */
1957 if (interrupt_input)
1958 unrequest_sigio ();
1960 loop:
1962 immediate_quit = 1;
1963 QUIT;
1965 if (connect (s, (struct sockaddr *) &address, sizeof address) == -1
1966 && errno != EISCONN)
1968 int xerrno = errno;
1970 immediate_quit = 0;
1972 if (errno == EINTR)
1973 goto loop;
1974 if (errno == EADDRINUSE && retry < 20)
1976 /* A delay here is needed on some FreeBSD systems,
1977 and it is harmless, since this retrying takes time anyway
1978 and should be infrequent. */
1979 Fsleep_for (make_number (1), Qnil);
1980 retry++;
1981 goto loop;
1984 /* Discard the unwind protect. */
1985 specpdl_ptr = specpdl + count1;
1987 emacs_close (s);
1989 if (interrupt_input)
1990 request_sigio ();
1992 errno = xerrno;
1993 report_file_error ("connection failed",
1994 Fcons (host, Fcons (name, Qnil)));
1996 #endif /* ! HAVE_GETADDRINFO */
1998 immediate_quit = 0;
2000 /* Discard the unwind protect. */
2001 specpdl_ptr = specpdl + count1;
2003 #ifdef POLL_FOR_INPUT
2004 unbind_to (count, Qnil);
2005 #endif
2007 if (interrupt_input)
2008 request_sigio ();
2010 #else /* TERM */
2011 s = connect_server (0);
2012 if (s < 0)
2013 report_file_error ("error creating socket", Fcons (name, Qnil));
2014 send_command (s, C_PORT, 0, "%s:%d", XSTRING (host)->data, ntohs (port));
2015 send_command (s, C_DUMB, 1, 0);
2016 #endif /* TERM */
2018 inch = s;
2019 outch = s;
2021 if (!NILP (buffer))
2022 buffer = Fget_buffer_create (buffer);
2023 proc = make_process (name);
2025 chan_process[inch] = proc;
2027 #ifdef O_NONBLOCK
2028 fcntl (inch, F_SETFL, O_NONBLOCK);
2029 #else
2030 #ifdef O_NDELAY
2031 fcntl (inch, F_SETFL, O_NDELAY);
2032 #endif
2033 #endif
2035 XPROCESS (proc)->childp = Fcons (host, Fcons (service, Qnil));
2036 XPROCESS (proc)->command_channel_p = Qnil;
2037 XPROCESS (proc)->buffer = buffer;
2038 XPROCESS (proc)->sentinel = Qnil;
2039 XPROCESS (proc)->filter = Qnil;
2040 XPROCESS (proc)->command = Qnil;
2041 XPROCESS (proc)->pid = Qnil;
2042 XSETINT (XPROCESS (proc)->infd, inch);
2043 XSETINT (XPROCESS (proc)->outfd, outch);
2044 XPROCESS (proc)->status = Qrun;
2045 FD_SET (inch, &input_wait_mask);
2046 FD_SET (inch, &non_keyboard_wait_mask);
2047 if (inch > max_process_desc)
2048 max_process_desc = inch;
2051 /* Setup coding systems for communicating with the network stream. */
2052 struct gcpro gcpro1;
2053 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
2054 Lisp_Object coding_systems = Qt;
2055 Lisp_Object args[5], val;
2057 if (!NILP (Vcoding_system_for_read))
2058 val = Vcoding_system_for_read;
2059 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2060 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2061 /* We dare not decode end-of-line format by setting VAL to
2062 Qraw_text, because the existing Emacs Lisp libraries
2063 assume that they receive bare code including a sequene of
2064 CR LF. */
2065 val = Qnil;
2066 else
2068 args[0] = Qopen_network_stream, args[1] = name,
2069 args[2] = buffer, args[3] = host, args[4] = service;
2070 GCPRO1 (proc);
2071 coding_systems = Ffind_operation_coding_system (5, args);
2072 UNGCPRO;
2073 if (CONSP (coding_systems))
2074 val = XCAR (coding_systems);
2075 else if (CONSP (Vdefault_process_coding_system))
2076 val = XCAR (Vdefault_process_coding_system);
2077 else
2078 val = Qnil;
2080 XPROCESS (proc)->decode_coding_system = val;
2082 if (!NILP (Vcoding_system_for_write))
2083 val = Vcoding_system_for_write;
2084 else if (NILP (current_buffer->enable_multibyte_characters))
2085 val = Qnil;
2086 else
2088 if (EQ (coding_systems, Qt))
2090 args[0] = Qopen_network_stream, args[1] = name,
2091 args[2] = buffer, args[3] = host, args[4] = service;
2092 GCPRO1 (proc);
2093 coding_systems = Ffind_operation_coding_system (5, args);
2094 UNGCPRO;
2096 if (CONSP (coding_systems))
2097 val = XCDR (coding_systems);
2098 else if (CONSP (Vdefault_process_coding_system))
2099 val = XCDR (Vdefault_process_coding_system);
2100 else
2101 val = Qnil;
2103 XPROCESS (proc)->encode_coding_system = val;
2106 if (!proc_decode_coding_system[inch])
2107 proc_decode_coding_system[inch]
2108 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
2109 setup_coding_system (XPROCESS (proc)->decode_coding_system,
2110 proc_decode_coding_system[inch]);
2111 if (!proc_encode_coding_system[outch])
2112 proc_encode_coding_system[outch]
2113 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
2114 setup_coding_system (XPROCESS (proc)->encode_coding_system,
2115 proc_encode_coding_system[outch]);
2117 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
2118 XPROCESS (proc)->decoding_carryover = make_number (0);
2119 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
2120 XPROCESS (proc)->encoding_carryover = make_number (0);
2122 XPROCESS (proc)->inherit_coding_system_flag
2123 = (NILP (buffer) || !inherit_process_coding_system
2124 ? Qnil : Qt);
2126 UNGCPRO;
2127 return proc;
2129 #endif /* HAVE_SOCKETS */
2131 void
2132 deactivate_process (proc)
2133 Lisp_Object proc;
2135 register int inchannel, outchannel;
2136 register struct Lisp_Process *p = XPROCESS (proc);
2138 inchannel = XINT (p->infd);
2139 outchannel = XINT (p->outfd);
2141 if (inchannel >= 0)
2143 /* Beware SIGCHLD hereabouts. */
2144 flush_pending_output (inchannel);
2145 #ifdef VMS
2147 VMS_PROC_STUFF *get_vms_process_pointer (), *vs;
2148 sys$dassgn (outchannel);
2149 vs = get_vms_process_pointer (p->pid);
2150 if (vs)
2151 give_back_vms_process_stuff (vs);
2153 #else
2154 emacs_close (inchannel);
2155 if (outchannel >= 0 && outchannel != inchannel)
2156 emacs_close (outchannel);
2157 #endif
2159 XSETINT (p->infd, -1);
2160 XSETINT (p->outfd, -1);
2161 chan_process[inchannel] = Qnil;
2162 FD_CLR (inchannel, &input_wait_mask);
2163 FD_CLR (inchannel, &non_keyboard_wait_mask);
2164 if (inchannel == max_process_desc)
2166 int i;
2167 /* We just closed the highest-numbered process input descriptor,
2168 so recompute the highest-numbered one now. */
2169 max_process_desc = 0;
2170 for (i = 0; i < MAXDESC; i++)
2171 if (!NILP (chan_process[i]))
2172 max_process_desc = i;
2177 /* Close all descriptors currently in use for communication
2178 with subprocess. This is used in a newly-forked subprocess
2179 to get rid of irrelevant descriptors. */
2181 void
2182 close_process_descs ()
2184 #ifndef WINDOWSNT
2185 int i;
2186 for (i = 0; i < MAXDESC; i++)
2188 Lisp_Object process;
2189 process = chan_process[i];
2190 if (!NILP (process))
2192 int in = XINT (XPROCESS (process)->infd);
2193 int out = XINT (XPROCESS (process)->outfd);
2194 if (in >= 0)
2195 emacs_close (in);
2196 if (out >= 0 && in != out)
2197 emacs_close (out);
2200 #endif
2203 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
2204 0, 3, 0,
2205 "Allow any pending output from subprocesses to be read by Emacs.\n\
2206 It is read into the process' buffers or given to their filter functions.\n\
2207 Non-nil arg PROCESS means do not return until some output has been received\n\
2208 from PROCESS.\n\
2209 Non-nil second arg TIMEOUT and third arg TIMEOUT-MSECS are number of\n\
2210 seconds and microseconds to wait; return after that much time whether\n\
2211 or not there is input.\n\
2212 Return non-nil iff we received any output before the timeout expired.")
2213 (process, timeout, timeout_msecs)
2214 register Lisp_Object process, timeout, timeout_msecs;
2216 int seconds;
2217 int useconds;
2219 if (! NILP (process))
2220 CHECK_PROCESS (process, 0);
2222 if (! NILP (timeout_msecs))
2224 CHECK_NUMBER (timeout_msecs, 2);
2225 useconds = XINT (timeout_msecs);
2226 if (!INTEGERP (timeout))
2227 XSETINT (timeout, 0);
2230 int carry = useconds / 1000000;
2232 XSETINT (timeout, XINT (timeout) + carry);
2233 useconds -= carry * 1000000;
2235 /* I think this clause is necessary because C doesn't
2236 guarantee a particular rounding direction for negative
2237 integers. */
2238 if (useconds < 0)
2240 XSETINT (timeout, XINT (timeout) - 1);
2241 useconds += 1000000;
2245 else
2246 useconds = 0;
2248 if (! NILP (timeout))
2250 CHECK_NUMBER (timeout, 1);
2251 seconds = XINT (timeout);
2252 if (seconds < 0 || (seconds == 0 && useconds == 0))
2253 seconds = -1;
2255 else
2257 if (NILP (process))
2258 seconds = -1;
2259 else
2260 seconds = 0;
2263 if (NILP (process))
2264 XSETFASTINT (process, 0);
2266 return
2267 (wait_reading_process_input (seconds, useconds, process, 0)
2268 ? Qt : Qnil);
2271 /* This variable is different from waiting_for_input in keyboard.c.
2272 It is used to communicate to a lisp process-filter/sentinel (via the
2273 function Fwaiting_for_user_input_p below) whether emacs was waiting
2274 for user-input when that process-filter was called.
2275 waiting_for_input cannot be used as that is by definition 0 when
2276 lisp code is being evalled.
2277 This is also used in record_asynch_buffer_change.
2278 For that purpose, this must be 0
2279 when not inside wait_reading_process_input. */
2280 static int waiting_for_user_input_p;
2282 /* This is here so breakpoints can be put on it. */
2283 static void
2284 wait_reading_process_input_1 ()
2288 /* Read and dispose of subprocess output while waiting for timeout to
2289 elapse and/or keyboard input to be available.
2291 TIME_LIMIT is:
2292 timeout in seconds, or
2293 zero for no limit, or
2294 -1 means gobble data immediately available but don't wait for any.
2296 MICROSECS is:
2297 an additional duration to wait, measured in microseconds.
2298 If this is nonzero and time_limit is 0, then the timeout
2299 consists of MICROSECS only.
2301 READ_KBD is a lisp value:
2302 0 to ignore keyboard input, or
2303 1 to return when input is available, or
2304 -1 meaning caller will actually read the input, so don't throw to
2305 the quit handler, or
2306 a cons cell, meaning wait until its car is non-nil
2307 (and gobble terminal input into the buffer if any arrives), or
2308 a process object, meaning wait until something arrives from that
2309 process. The return value is true iff we read some input from
2310 that process.
2312 DO_DISPLAY != 0 means redisplay should be done to show subprocess
2313 output that arrives.
2315 If READ_KBD is a pointer to a struct Lisp_Process, then the
2316 function returns true iff we received input from that process
2317 before the timeout elapsed.
2318 Otherwise, return true iff we received input from any process. */
2321 wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
2322 int time_limit, microsecs;
2323 Lisp_Object read_kbd;
2324 int do_display;
2326 register int channel, nfds;
2327 static SELECT_TYPE Available;
2328 int xerrno;
2329 Lisp_Object proc;
2330 EMACS_TIME timeout, end_time;
2331 SELECT_TYPE Atemp;
2332 int wait_channel = -1;
2333 struct Lisp_Process *wait_proc = 0;
2334 int got_some_input = 0;
2335 Lisp_Object *wait_for_cell = 0;
2337 FD_ZERO (&Available);
2339 /* If read_kbd is a process to watch, set wait_proc and wait_channel
2340 accordingly. */
2341 if (PROCESSP (read_kbd))
2343 wait_proc = XPROCESS (read_kbd);
2344 wait_channel = XINT (wait_proc->infd);
2345 XSETFASTINT (read_kbd, 0);
2348 /* If waiting for non-nil in a cell, record where. */
2349 if (CONSP (read_kbd))
2351 wait_for_cell = &XCAR (read_kbd);
2352 XSETFASTINT (read_kbd, 0);
2355 waiting_for_user_input_p = XINT (read_kbd);
2357 /* Since we may need to wait several times,
2358 compute the absolute time to return at. */
2359 if (time_limit || microsecs)
2361 EMACS_GET_TIME (end_time);
2362 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
2363 EMACS_ADD_TIME (end_time, end_time, timeout);
2365 #ifdef hpux
2366 /* AlainF 5-Jul-1996
2367 HP-UX 10.10 seem to have problems with signals coming in
2368 Causes "poll: interrupted system call" messages when Emacs is run
2369 in an X window
2370 Turn off periodic alarms (in case they are in use) */
2371 stop_polling ();
2372 #endif
2374 while (1)
2376 int timeout_reduced_for_timers = 0;
2378 #ifdef HAVE_X_WINDOWS
2379 if (display_busy_cursor_p)
2380 Fx_hide_busy_cursor (Qnil);
2381 #endif
2383 /* If calling from keyboard input, do not quit
2384 since we want to return C-g as an input character.
2385 Otherwise, do pending quit if requested. */
2386 if (XINT (read_kbd) >= 0)
2387 QUIT;
2389 /* Exit now if the cell we're waiting for became non-nil. */
2390 if (wait_for_cell && ! NILP (*wait_for_cell))
2391 break;
2393 /* Compute time from now till when time limit is up */
2394 /* Exit if already run out */
2395 if (time_limit == -1)
2397 /* -1 specified for timeout means
2398 gobble output available now
2399 but don't wait at all. */
2401 EMACS_SET_SECS_USECS (timeout, 0, 0);
2403 else if (time_limit || microsecs)
2405 EMACS_GET_TIME (timeout);
2406 EMACS_SUB_TIME (timeout, end_time, timeout);
2407 if (EMACS_TIME_NEG_P (timeout))
2408 break;
2410 else
2412 EMACS_SET_SECS_USECS (timeout, 100000, 0);
2415 /* Normally we run timers here.
2416 But not if wait_for_cell; in those cases,
2417 the wait is supposed to be short,
2418 and those callers cannot handle running arbitrary Lisp code here. */
2419 if (! wait_for_cell)
2421 EMACS_TIME timer_delay;
2422 int old_timers_run;
2424 retry:
2425 old_timers_run = timers_run;
2426 timer_delay = timer_check (1);
2427 if (timers_run != old_timers_run && do_display)
2429 redisplay_preserve_echo_area ();
2430 /* We must retry, since a timer may have requeued itself
2431 and that could alter the time_delay. */
2432 goto retry;
2435 /* If there is unread keyboard input, also return. */
2436 if (XINT (read_kbd) != 0
2437 && requeued_events_pending_p ())
2438 break;
2440 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
2442 EMACS_TIME difference;
2443 EMACS_SUB_TIME (difference, timer_delay, timeout);
2444 if (EMACS_TIME_NEG_P (difference))
2446 timeout = timer_delay;
2447 timeout_reduced_for_timers = 1;
2450 /* If time_limit is -1, we are not going to wait at all. */
2451 else if (time_limit != -1)
2453 /* This is so a breakpoint can be put here. */
2454 wait_reading_process_input_1 ();
2458 /* Cause C-g and alarm signals to take immediate action,
2459 and cause input available signals to zero out timeout.
2461 It is important that we do this before checking for process
2462 activity. If we get a SIGCHLD after the explicit checks for
2463 process activity, timeout is the only way we will know. */
2464 if (XINT (read_kbd) < 0)
2465 set_waiting_for_input (&timeout);
2467 /* If status of something has changed, and no input is
2468 available, notify the user of the change right away. After
2469 this explicit check, we'll let the SIGCHLD handler zap
2470 timeout to get our attention. */
2471 if (update_tick != process_tick && do_display)
2473 Atemp = input_wait_mask;
2474 EMACS_SET_SECS_USECS (timeout, 0, 0);
2475 if ((select (max (max_process_desc, max_keyboard_desc) + 1,
2476 &Atemp, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
2477 &timeout)
2478 <= 0))
2480 /* It's okay for us to do this and then continue with
2481 the loop, since timeout has already been zeroed out. */
2482 clear_waiting_for_input ();
2483 status_notify ();
2487 /* Don't wait for output from a non-running process. */
2488 if (wait_proc != 0 && !NILP (wait_proc->raw_status_low))
2489 update_status (wait_proc);
2490 if (wait_proc != 0
2491 && ! EQ (wait_proc->status, Qrun))
2493 int nread, total_nread = 0;
2495 clear_waiting_for_input ();
2496 XSETPROCESS (proc, wait_proc);
2498 /* Read data from the process, until we exhaust it. */
2499 while (XINT (wait_proc->infd) >= 0)
2501 nread = read_process_output (proc, XINT (wait_proc->infd));
2503 if (nread == 0)
2504 break;
2506 if (0 < nread)
2507 total_nread += nread;
2508 #ifdef EIO
2509 else if (nread == -1 && EIO == errno)
2510 break;
2511 #endif
2512 #ifdef EAGAIN
2513 else if (nread == -1 && EAGAIN == errno)
2514 break;
2515 #endif
2516 #ifdef EWOULDBLOCK
2517 else if (nread == -1 && EWOULDBLOCK == errno)
2518 break;
2519 #endif
2521 if (total_nread > 0 && do_display)
2522 redisplay_preserve_echo_area ();
2524 break;
2527 /* Wait till there is something to do */
2529 if (wait_for_cell)
2530 Available = non_process_wait_mask;
2531 else if (! XINT (read_kbd))
2532 Available = non_keyboard_wait_mask;
2533 else
2534 Available = input_wait_mask;
2536 /* If frame size has changed or the window is newly mapped,
2537 redisplay now, before we start to wait. There is a race
2538 condition here; if a SIGIO arrives between now and the select
2539 and indicates that a frame is trashed, the select may block
2540 displaying a trashed screen. */
2541 if (frame_garbaged && do_display)
2543 clear_waiting_for_input ();
2544 redisplay_preserve_echo_area ();
2545 if (XINT (read_kbd) < 0)
2546 set_waiting_for_input (&timeout);
2549 if (XINT (read_kbd) && detect_input_pending ())
2551 nfds = 0;
2552 FD_ZERO (&Available);
2554 else
2555 nfds = select (max (max_process_desc, max_keyboard_desc) + 1,
2556 &Available, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
2557 &timeout);
2559 xerrno = errno;
2561 /* Make C-g and alarm signals set flags again */
2562 clear_waiting_for_input ();
2564 /* If we woke up due to SIGWINCH, actually change size now. */
2565 do_pending_window_change (0);
2567 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
2568 /* We wanted the full specified time, so return now. */
2569 break;
2570 if (nfds < 0)
2572 if (xerrno == EINTR)
2573 FD_ZERO (&Available);
2574 #ifdef ultrix
2575 /* Ultrix select seems to return ENOMEM when it is
2576 interrupted. Treat it just like EINTR. Bleah. Note
2577 that we want to test for the "ultrix" CPP symbol, not
2578 "__ultrix__"; the latter is only defined under GCC, but
2579 not by DEC's bundled CC. -JimB */
2580 else if (xerrno == ENOMEM)
2581 FD_ZERO (&Available);
2582 #endif
2583 #ifdef ALLIANT
2584 /* This happens for no known reason on ALLIANT.
2585 I am guessing that this is the right response. -- RMS. */
2586 else if (xerrno == EFAULT)
2587 FD_ZERO (&Available);
2588 #endif
2589 else if (xerrno == EBADF)
2591 #ifdef AIX
2592 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
2593 the child's closure of the pts gives the parent a SIGHUP, and
2594 the ptc file descriptor is automatically closed,
2595 yielding EBADF here or at select() call above.
2596 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
2597 in m/ibmrt-aix.h), and here we just ignore the select error.
2598 Cleanup occurs c/o status_notify after SIGCLD. */
2599 FD_ZERO (&Available); /* Cannot depend on values returned */
2600 #else
2601 abort ();
2602 #endif
2604 else
2605 error ("select error: %s", emacs_strerror (xerrno));
2607 #if defined(sun) && !defined(USG5_4)
2608 else if (nfds > 0 && keyboard_bit_set (&Available)
2609 && interrupt_input)
2610 /* System sometimes fails to deliver SIGIO.
2612 David J. Mackenzie says that Emacs doesn't compile under
2613 Solaris if this code is enabled, thus the USG5_4 in the CPP
2614 conditional. "I haven't noticed any ill effects so far.
2615 If you find a Solaris expert somewhere, they might know
2616 better." */
2617 kill (getpid (), SIGIO);
2618 #endif
2620 #if 0 /* When polling is used, interrupt_input is 0,
2621 so get_input_pending should read the input.
2622 So this should not be needed. */
2623 /* If we are using polling for input,
2624 and we see input available, make it get read now.
2625 Otherwise it might not actually get read for a second.
2626 And on hpux, since we turn off polling in wait_reading_process_input,
2627 it might never get read at all if we don't spend much time
2628 outside of wait_reading_process_input. */
2629 if (XINT (read_kbd) && interrupt_input
2630 && keyboard_bit_set (&Available)
2631 && input_polling_used ())
2632 kill (getpid (), SIGALRM);
2633 #endif
2635 /* Check for keyboard input */
2636 /* If there is any, return immediately
2637 to give it higher priority than subprocesses */
2639 if (XINT (read_kbd) != 0
2640 && detect_input_pending_run_timers (do_display))
2642 swallow_events (do_display);
2643 if (detect_input_pending_run_timers (do_display))
2644 break;
2647 /* If there is unread keyboard input, also return. */
2648 if (XINT (read_kbd) != 0
2649 && requeued_events_pending_p ())
2650 break;
2652 /* If we are not checking for keyboard input now,
2653 do process events (but don't run any timers).
2654 This is so that X events will be processed.
2655 Otherwise they may have to wait until polling takes place.
2656 That would causes delays in pasting selections, for example.
2658 (We used to do this only if wait_for_cell.) */
2659 if (XINT (read_kbd) == 0 && detect_input_pending ())
2661 swallow_events (do_display);
2662 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
2663 if (detect_input_pending ())
2664 break;
2665 #endif
2668 /* Exit now if the cell we're waiting for became non-nil. */
2669 if (wait_for_cell && ! NILP (*wait_for_cell))
2670 break;
2672 #ifdef SIGIO
2673 /* If we think we have keyboard input waiting, but didn't get SIGIO,
2674 go read it. This can happen with X on BSD after logging out.
2675 In that case, there really is no input and no SIGIO,
2676 but select says there is input. */
2678 if (XINT (read_kbd) && interrupt_input
2679 && keyboard_bit_set (&Available))
2680 kill (getpid (), SIGIO);
2681 #endif
2683 if (! wait_proc)
2684 got_some_input |= nfds > 0;
2686 /* If checking input just got us a size-change event from X,
2687 obey it now if we should. */
2688 if (XINT (read_kbd) || wait_for_cell)
2689 do_pending_window_change (0);
2691 /* Check for data from a process. */
2692 /* Really FIRST_PROC_DESC should be 0 on Unix,
2693 but this is safer in the short run. */
2694 for (channel = 0; channel <= max_process_desc; channel++)
2696 if (FD_ISSET (channel, &Available)
2697 && FD_ISSET (channel, &non_keyboard_wait_mask))
2699 int nread;
2701 /* If waiting for this channel, arrange to return as
2702 soon as no more input to be processed. No more
2703 waiting. */
2704 if (wait_channel == channel)
2706 wait_channel = -1;
2707 time_limit = -1;
2708 got_some_input = 1;
2710 proc = chan_process[channel];
2711 if (NILP (proc))
2712 continue;
2714 /* Read data from the process, starting with our
2715 buffered-ahead character if we have one. */
2717 nread = read_process_output (proc, channel);
2718 if (nread > 0)
2720 /* Since read_process_output can run a filter,
2721 which can call accept-process-output,
2722 don't try to read from any other processes
2723 before doing the select again. */
2724 FD_ZERO (&Available);
2726 if (do_display)
2727 redisplay_preserve_echo_area ();
2729 #ifdef EWOULDBLOCK
2730 else if (nread == -1 && errno == EWOULDBLOCK)
2732 #endif
2733 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
2734 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
2735 #ifdef O_NONBLOCK
2736 else if (nread == -1 && errno == EAGAIN)
2738 #else
2739 #ifdef O_NDELAY
2740 else if (nread == -1 && errno == EAGAIN)
2742 /* Note that we cannot distinguish between no input
2743 available now and a closed pipe.
2744 With luck, a closed pipe will be accompanied by
2745 subprocess termination and SIGCHLD. */
2746 else if (nread == 0 && !NETCONN_P (proc))
2748 #endif /* O_NDELAY */
2749 #endif /* O_NONBLOCK */
2750 #ifdef HAVE_PTYS
2751 /* On some OSs with ptys, when the process on one end of
2752 a pty exits, the other end gets an error reading with
2753 errno = EIO instead of getting an EOF (0 bytes read).
2754 Therefore, if we get an error reading and errno =
2755 EIO, just continue, because the child process has
2756 exited and should clean itself up soon (e.g. when we
2757 get a SIGCHLD).
2759 However, it has been known to happen that the SIGCHLD
2760 got lost. So raise the signl again just in case.
2761 It can't hurt. */
2762 else if (nread == -1 && errno == EIO)
2763 kill (getpid (), SIGCHLD);
2764 #endif /* HAVE_PTYS */
2765 /* If we can detect process termination, don't consider the process
2766 gone just because its pipe is closed. */
2767 #ifdef SIGCHLD
2768 else if (nread == 0 && !NETCONN_P (proc))
2770 #endif
2771 else
2773 /* Preserve status of processes already terminated. */
2774 XSETINT (XPROCESS (proc)->tick, ++process_tick);
2775 deactivate_process (proc);
2776 if (!NILP (XPROCESS (proc)->raw_status_low))
2777 update_status (XPROCESS (proc));
2778 if (EQ (XPROCESS (proc)->status, Qrun))
2779 XPROCESS (proc)->status
2780 = Fcons (Qexit, Fcons (make_number (256), Qnil));
2783 } /* end for each file descriptor */
2784 } /* end while exit conditions not met */
2786 waiting_for_user_input_p = 0;
2788 /* If calling from keyboard input, do not quit
2789 since we want to return C-g as an input character.
2790 Otherwise, do pending quit if requested. */
2791 if (XINT (read_kbd) >= 0)
2793 /* Prevent input_pending from remaining set if we quit. */
2794 clear_input_pending ();
2795 QUIT;
2797 #ifdef hpux
2798 /* AlainF 5-Jul-1996
2799 HP-UX 10.10 seems to have problems with signals coming in
2800 Causes "poll: interrupted system call" messages when Emacs is run
2801 in an X window
2802 Turn periodic alarms back on */
2803 start_polling ();
2804 #endif
2806 #ifdef HAVE_X_WINDOWS
2807 if (display_busy_cursor_p)
2808 if (!inhibit_busy_cursor)
2809 Fx_show_busy_cursor ();
2810 #endif
2812 return got_some_input;
2815 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
2817 static Lisp_Object
2818 read_process_output_call (fun_and_args)
2819 Lisp_Object fun_and_args;
2821 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
2824 static Lisp_Object
2825 read_process_output_error_handler (error)
2826 Lisp_Object error;
2828 cmd_error_internal (error, "error in process filter: ");
2829 Vinhibit_quit = Qt;
2830 update_echo_area ();
2831 Fsleep_for (make_number (2), Qnil);
2834 /* Read pending output from the process channel,
2835 starting with our buffered-ahead character if we have one.
2836 Yield number of decoded characters read.
2838 This function reads at most 1024 characters.
2839 If you want to read all available subprocess output,
2840 you must call it repeatedly until it returns zero.
2842 The characters read are decoded according to PROC's coding-system
2843 for decoding. */
2846 read_process_output (proc, channel)
2847 Lisp_Object proc;
2848 register int channel;
2850 register int nchars, nbytes;
2851 char *chars;
2852 #ifdef VMS
2853 int chars_allocated = 0; /* If 1, `chars' should be freed later. */
2854 #else
2855 char buf[1024];
2856 #endif
2857 register Lisp_Object outstream;
2858 register struct buffer *old = current_buffer;
2859 register struct Lisp_Process *p = XPROCESS (proc);
2860 register int opoint;
2861 struct coding_system *coding = proc_decode_coding_system[channel];
2862 int chars_in_decoding_buf = 0; /* If 1, `chars' points
2863 XSTRING (p->decoding_buf)->data. */
2864 int carryover = XINT (p->decoding_carryover);
2866 #ifdef VMS
2867 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
2869 vs = get_vms_process_pointer (p->pid);
2870 if (vs)
2872 if (!vs->iosb[0])
2873 return (0); /* Really weird if it does this */
2874 if (!(vs->iosb[0] & 1))
2875 return -1; /* I/O error */
2877 else
2878 error ("Could not get VMS process pointer");
2879 chars = vs->inputBuffer;
2880 nbytes = clean_vms_buffer (chars, vs->iosb[1]);
2881 if (nbytes <= 0)
2883 start_vms_process_read (vs); /* Crank up the next read on the process */
2884 return 1; /* Nothing worth printing, say we got 1 */
2886 if (carryover > 0)
2888 /* The data carried over in the previous decoding (which are at
2889 the tail of decoding buffer) should be prepended to the new
2890 data read to decode all together. */
2891 char *buf = (char *) xmalloc (nbytes + carryover);
2893 bcopy (XSTRING (p->decoding_buf)->data
2894 + STRING_BYTES (XSTRING (p->decoding_buf)) - carryover,
2895 buf, carryover);
2896 bcopy (chars, buf + carryover, nbytes);
2897 chars = buf;
2898 chars_allocated = 1;
2900 #else /* not VMS */
2902 if (carryover)
2903 /* See the comment above. */
2904 bcopy (XSTRING (p->decoding_buf)->data
2905 + STRING_BYTES (XSTRING (p->decoding_buf)) - carryover,
2906 buf, carryover);
2908 if (proc_buffered_char[channel] < 0)
2909 nbytes = emacs_read (channel, buf + carryover, (sizeof buf) - carryover);
2910 else
2912 buf[carryover] = proc_buffered_char[channel];
2913 proc_buffered_char[channel] = -1;
2914 nbytes = emacs_read (channel, buf + carryover + 1,
2915 (sizeof buf) - carryover - 1);
2916 if (nbytes < 0)
2917 nbytes = 1;
2918 else
2919 nbytes = nbytes + 1;
2921 chars = buf;
2922 #endif /* not VMS */
2924 XSETINT (p->decoding_carryover, 0);
2926 /* At this point, NBYTES holds number of characters just received
2927 (including the one in proc_buffered_char[channel]). */
2928 if (nbytes <= 0)
2930 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
2931 return nbytes;
2932 coding->mode |= CODING_MODE_LAST_BLOCK;
2935 /* Now set NBYTES how many bytes we must decode. */
2936 nbytes += carryover;
2937 nchars = nbytes;
2939 if (CODING_MAY_REQUIRE_DECODING (coding))
2941 int require = decoding_buffer_size (coding, nbytes);
2942 int result;
2944 if (STRING_BYTES (XSTRING (p->decoding_buf)) < require)
2945 p->decoding_buf = make_uninit_string (require);
2946 result = decode_coding (coding, chars, XSTRING (p->decoding_buf)->data,
2947 nbytes, STRING_BYTES (XSTRING (p->decoding_buf)));
2948 carryover = nbytes - coding->consumed;
2949 if (carryover > 0)
2951 /* Copy the carryover bytes to the end of p->decoding_buf, to
2952 be processed on the next read. Since decoding_buffer_size
2953 asks for an extra amount of space beyond the maximum
2954 expected for the output, there should always be sufficient
2955 space for the carryover (which is by definition a sequence
2956 of bytes that was not long enough to be decoded, and thus
2957 has a bounded length). */
2958 if (STRING_BYTES (XSTRING (p->decoding_buf))
2959 < coding->produced + carryover)
2960 abort ();
2961 bcopy (chars + coding->consumed,
2962 XSTRING (p->decoding_buf)->data
2963 + STRING_BYTES (XSTRING (p->decoding_buf)) - carryover,
2964 carryover);
2965 XSETINT (p->decoding_carryover, carryover);
2968 /* A new coding system might be found by `decode_coding'. */
2969 if (!EQ (p->decode_coding_system, coding->symbol))
2971 p->decode_coding_system = coding->symbol;
2973 /* Don't call setup_coding_system for
2974 proc_decode_coding_system[channel] here. It is done in
2975 detect_coding called via decode_coding above. */
2977 /* If a coding system for encoding is not yet decided, we set
2978 it as the same as coding-system for decoding.
2980 But, before doing that we must check if
2981 proc_encode_coding_system[p->outfd] surely points to a
2982 valid memory because p->outfd will be changed once EOF is
2983 sent to the process. */
2984 if (NILP (p->encode_coding_system)
2985 && proc_encode_coding_system[XINT (p->outfd)])
2987 p->encode_coding_system = coding->symbol;
2988 setup_coding_system (coding->symbol,
2989 proc_encode_coding_system[XINT (p->outfd)]);
2993 #ifdef VMS
2994 /* Now we don't need the contents of `chars'. */
2995 if (chars_allocated)
2996 free (chars);
2997 #endif
2998 if (coding->produced == 0)
2999 return 0;
3000 chars = (char *) XSTRING (p->decoding_buf)->data;
3001 nbytes = coding->produced;
3002 nchars = (coding->fake_multibyte
3003 ? multibyte_chars_in_text (chars, nbytes)
3004 : coding->produced_char);
3005 chars_in_decoding_buf = 1;
3007 else
3009 #ifdef VMS
3010 if (chars_allocated)
3012 /* Although we don't have to decode the received data, we
3013 must move it to an area which we don't have to free. */
3014 if (! STRINGP (p->decoding_buf)
3015 || STRING_BYTES (XSTRING (p->decoding_buf)) < nbytes)
3016 p->decoding_buf = make_uninit_string (nbytes);
3017 bcopy (chars, XSTRING (p->decoding_buf)->data, nbytes);
3018 free (chars);
3019 chars = XSTRING (p->decoding_buf)->data;
3020 chars_in_decoding_buf = 1;
3022 #endif
3023 nchars = multibyte_chars_in_text (chars, nbytes);
3026 Vlast_coding_system_used = coding->symbol;
3028 /* If the caller required, let the process associated buffer
3029 inherit the coding-system used to decode the process output. */
3030 if (! NILP (p->inherit_coding_system_flag)
3031 && !NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
3033 struct buffer *prev_buf = current_buffer;
3035 Fset_buffer (p->buffer);
3036 call1 (intern ("after-insert-file-set-buffer-file-coding-system"),
3037 make_number (nbytes));
3038 set_buffer_internal (prev_buf);
3041 /* Read and dispose of the process output. */
3042 outstream = p->filter;
3043 if (!NILP (outstream))
3045 /* We inhibit quit here instead of just catching it so that
3046 hitting ^G when a filter happens to be running won't screw
3047 it up. */
3048 int count = specpdl_ptr - specpdl;
3049 Lisp_Object odeactivate;
3050 Lisp_Object obuffer, okeymap;
3051 Lisp_Object text;
3052 int outer_running_asynch_code = running_asynch_code;
3053 int waiting = waiting_for_user_input_p;
3055 /* No need to gcpro these, because all we do with them later
3056 is test them for EQness, and none of them should be a string. */
3057 odeactivate = Vdeactivate_mark;
3058 XSETBUFFER (obuffer, current_buffer);
3059 okeymap = current_buffer->keymap;
3061 specbind (Qinhibit_quit, Qt);
3062 specbind (Qlast_nonmenu_event, Qt);
3064 /* In case we get recursively called,
3065 and we already saved the match data nonrecursively,
3066 save the same match data in safely recursive fashion. */
3067 if (outer_running_asynch_code)
3069 Lisp_Object tem;
3070 /* Don't clobber the CURRENT match data, either! */
3071 tem = Fmatch_data (Qnil, Qnil);
3072 restore_match_data ();
3073 record_unwind_protect (Fset_match_data, Fmatch_data (Qnil, Qnil));
3074 Fset_match_data (tem);
3077 /* For speed, if a search happens within this code,
3078 save the match data in a special nonrecursive fashion. */
3079 running_asynch_code = 1;
3081 /* The multibyteness of a string given to the filter is decided
3082 by which coding system we used for decoding. */
3083 if (coding->type == coding_type_no_conversion
3084 || coding->type == coding_type_raw_text)
3085 text = make_unibyte_string (chars, nbytes);
3086 else
3087 text = make_multibyte_string (chars, nchars, nbytes);
3089 internal_condition_case_1 (read_process_output_call,
3090 Fcons (outstream,
3091 Fcons (proc, Fcons (text, Qnil))),
3092 !NILP (Vdebug_on_error) ? Qnil : Qerror,
3093 read_process_output_error_handler);
3095 /* If we saved the match data nonrecursively, restore it now. */
3096 restore_match_data ();
3097 running_asynch_code = outer_running_asynch_code;
3099 /* Handling the process output should not deactivate the mark. */
3100 Vdeactivate_mark = odeactivate;
3102 /* Restore waiting_for_user_input_p as it was
3103 when we were called, in case the filter clobbered it. */
3104 waiting_for_user_input_p = waiting;
3106 #if 0 /* Call record_asynch_buffer_change unconditionally,
3107 because we might have changed minor modes or other things
3108 that affect key bindings. */
3109 if (! EQ (Fcurrent_buffer (), obuffer)
3110 || ! EQ (current_buffer->keymap, okeymap))
3111 #endif
3112 /* But do it only if the caller is actually going to read events.
3113 Otherwise there's no need to make him wake up, and it could
3114 cause trouble (for example it would make Fsit_for return). */
3115 if (waiting_for_user_input_p == -1)
3116 record_asynch_buffer_change ();
3118 #ifdef VMS
3119 start_vms_process_read (vs);
3120 #endif
3121 unbind_to (count, Qnil);
3122 return nchars;
3125 /* If no filter, write into buffer if it isn't dead. */
3126 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
3128 Lisp_Object old_read_only;
3129 int old_begv, old_zv;
3130 int old_begv_byte, old_zv_byte;
3131 Lisp_Object odeactivate;
3132 int before, before_byte;
3133 int opoint_byte;
3135 odeactivate = Vdeactivate_mark;
3137 Fset_buffer (p->buffer);
3138 opoint = PT;
3139 opoint_byte = PT_BYTE;
3140 old_read_only = current_buffer->read_only;
3141 old_begv = BEGV;
3142 old_zv = ZV;
3143 old_begv_byte = BEGV_BYTE;
3144 old_zv_byte = ZV_BYTE;
3146 current_buffer->read_only = Qnil;
3148 /* Insert new output into buffer
3149 at the current end-of-output marker,
3150 thus preserving logical ordering of input and output. */
3151 if (XMARKER (p->mark)->buffer)
3152 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
3153 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
3154 ZV_BYTE));
3155 else
3156 SET_PT_BOTH (ZV, ZV_BYTE);
3157 before = PT;
3158 before_byte = PT_BYTE;
3160 /* If the output marker is outside of the visible region, save
3161 the restriction and widen. */
3162 if (! (BEGV <= PT && PT <= ZV))
3163 Fwiden ();
3165 if (NILP (current_buffer->enable_multibyte_characters))
3166 nchars = nbytes;
3168 /* Insert before markers in case we are inserting where
3169 the buffer's mark is, and the user's next command is Meta-y. */
3170 if (chars_in_decoding_buf)
3172 /* Since multibyteness of p->docoding_buf is corrupted, we
3173 can't use insert_from_string_before_markers. */
3174 char *temp_buf;
3176 temp_buf = (char *) alloca (nbytes);
3177 bcopy (XSTRING (p->decoding_buf)->data, temp_buf, nbytes);
3178 insert_before_markers (temp_buf, nbytes);
3180 else
3182 insert_1_both (chars, nchars, nbytes, 0, 1, 1);
3183 signal_after_change (opoint, 0, PT - opoint);
3185 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
3187 update_mode_lines++;
3189 /* Make sure opoint and the old restrictions
3190 float ahead of any new text just as point would. */
3191 if (opoint >= before)
3193 opoint += PT - before;
3194 opoint_byte += PT_BYTE - before_byte;
3196 if (old_begv > before)
3198 old_begv += PT - before;
3199 old_begv_byte += PT_BYTE - before_byte;
3201 if (old_zv >= before)
3203 old_zv += PT - before;
3204 old_zv_byte += PT_BYTE - before_byte;
3207 /* If the restriction isn't what it should be, set it. */
3208 if (old_begv != BEGV || old_zv != ZV)
3209 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
3211 /* Handling the process output should not deactivate the mark. */
3212 Vdeactivate_mark = odeactivate;
3214 current_buffer->read_only = old_read_only;
3215 SET_PT_BOTH (opoint, opoint_byte);
3216 set_buffer_internal (old);
3218 #ifdef VMS
3219 start_vms_process_read (vs);
3220 #endif
3221 return nbytes;
3224 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
3225 0, 0, 0,
3226 "Returns non-nil if emacs is waiting for input from the user.\n\
3227 This is intended for use by asynchronous process output filters and sentinels.")
3230 return (waiting_for_user_input_p ? Qt : Qnil);
3233 /* Sending data to subprocess */
3235 jmp_buf send_process_frame;
3237 SIGTYPE
3238 send_process_trap ()
3240 #ifdef BSD4_1
3241 sigrelse (SIGPIPE);
3242 sigrelse (SIGALRM);
3243 #endif /* BSD4_1 */
3244 longjmp (send_process_frame, 1);
3247 /* Send some data to process PROC.
3248 BUF is the beginning of the data; LEN is the number of characters.
3249 OBJECT is the Lisp object that the data comes from.
3251 The data is encoded by PROC's coding-system for encoding before it
3252 is sent. But if the data ends at the middle of multi-byte
3253 representation, that incomplete sequence of bytes are sent without
3254 being encoded. Should we store them in a buffer to prepend them to
3255 the data send later? */
3257 void
3258 send_process (proc, buf, len, object)
3259 volatile Lisp_Object proc;
3260 unsigned char *buf;
3261 int len;
3262 Lisp_Object object;
3264 /* Use volatile to protect variables from being clobbered by longjmp. */
3265 int rv;
3266 volatile unsigned char *procname = XSTRING (XPROCESS (proc)->name)->data;
3267 struct coding_system *coding;
3268 struct gcpro gcpro1;
3269 int carryover = XINT (XPROCESS (proc)->encoding_carryover);
3271 GCPRO1 (object);
3273 #ifdef VMS
3274 struct Lisp_Process *p = XPROCESS (proc);
3275 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
3276 #endif /* VMS */
3278 if (! NILP (XPROCESS (proc)->raw_status_low))
3279 update_status (XPROCESS (proc));
3280 if (! EQ (XPROCESS (proc)->status, Qrun))
3281 error ("Process %s not running", procname);
3282 if (XINT (XPROCESS (proc)->outfd) < 0)
3283 error ("Output file descriptor of %s is closed", procname);
3285 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
3286 Vlast_coding_system_used = coding->symbol;
3288 if (CODING_REQUIRE_ENCODING (coding))
3290 int require = encoding_buffer_size (coding, len);
3291 int offset;
3292 unsigned char *temp_buf = NULL;
3294 /* Remember the offset of data because a string or a buffer may
3295 be relocated. Setting OFFSET to -1 means we don't have to
3296 care about relocation. */
3297 offset = (BUFFERP (object)
3298 ? BUF_PTR_BYTE_POS (XBUFFER (object), buf)
3299 : (STRINGP (object)
3300 ? buf - XSTRING (object)->data
3301 : -1));
3303 if (carryover > 0)
3305 temp_buf = (unsigned char *) xmalloc (len + carryover);
3307 if (offset >= 0)
3309 if (BUFFERP (object))
3310 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
3311 else if (STRINGP (object))
3312 buf = offset + XSTRING (object)->data;
3313 /* Now we don't have to care about relocation. */
3314 offset = -1;
3316 bcopy ((XSTRING (XPROCESS (proc)->encoding_buf)->data
3317 + STRING_BYTES (XSTRING (XPROCESS (proc)->encoding_buf))
3318 - carryover),
3319 temp_buf,
3320 carryover);
3321 bcopy (buf, temp_buf + carryover, len);
3322 buf = temp_buf;
3325 if (STRING_BYTES (XSTRING (XPROCESS (proc)->encoding_buf)) < require)
3327 XPROCESS (proc)->encoding_buf = make_uninit_string (require);
3329 if (offset >= 0)
3331 if (BUFFERP (object))
3332 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
3333 else if (STRINGP (object))
3334 buf = offset + XSTRING (object)->data;
3337 object = XPROCESS (proc)->encoding_buf;
3338 encode_coding (coding, buf, XSTRING (object)->data,
3339 len, STRING_BYTES (XSTRING (object)));
3340 len = coding->produced;
3341 buf = XSTRING (object)->data;
3342 if (temp_buf)
3343 xfree (temp_buf);
3346 #ifdef VMS
3347 vs = get_vms_process_pointer (p->pid);
3348 if (vs == 0)
3349 error ("Could not find this process: %x", p->pid);
3350 else if (write_to_vms_process (vs, buf, len))
3352 #else
3354 if (pty_max_bytes == 0)
3356 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
3357 pty_max_bytes = fpathconf (XFASTINT (XPROCESS (proc)->outfd),
3358 _PC_MAX_CANON);
3359 if (pty_max_bytes < 0)
3360 pty_max_bytes = 250;
3361 #else
3362 pty_max_bytes = 250;
3363 #endif
3364 /* Deduct one, to leave space for the eof. */
3365 pty_max_bytes--;
3368 if (!setjmp (send_process_frame))
3369 while (len > 0)
3371 int this = len;
3372 SIGTYPE (*old_sigpipe)();
3374 /* Decide how much data we can send in one batch.
3375 Long lines need to be split into multiple batches. */
3376 if (!NILP (XPROCESS (proc)->pty_flag))
3378 /* Starting this at zero is always correct when not the first iteration
3379 because the previous iteration ended by sending C-d.
3380 It may not be correct for the first iteration
3381 if a partial line was sent in a separate send_process call.
3382 If that proves worth handling, we need to save linepos
3383 in the process object. */
3384 int linepos = 0;
3385 unsigned char *ptr = buf;
3386 unsigned char *end = buf + len;
3388 /* Scan through this text for a line that is too long. */
3389 while (ptr != end && linepos < pty_max_bytes)
3391 if (*ptr == '\n')
3392 linepos = 0;
3393 else
3394 linepos++;
3395 ptr++;
3397 /* If we found one, break the line there
3398 and put in a C-d to force the buffer through. */
3399 this = ptr - buf;
3402 /* Send this batch, using one or more write calls. */
3403 while (this > 0)
3405 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
3406 rv = emacs_write (XINT (XPROCESS (proc)->outfd), buf, this);
3407 signal (SIGPIPE, old_sigpipe);
3409 if (rv < 0)
3411 if (0
3412 #ifdef EWOULDBLOCK
3413 || errno == EWOULDBLOCK
3414 #endif
3415 #ifdef EAGAIN
3416 || errno == EAGAIN
3417 #endif
3419 /* Buffer is full. Wait, accepting input;
3420 that may allow the program
3421 to finish doing output and read more. */
3423 Lisp_Object zero;
3424 int offset;
3426 /* Running filters might relocate buffers or strings.
3427 Arrange to relocate BUF. */
3428 if (BUFFERP (object))
3429 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
3430 else if (STRINGP (object))
3431 offset = buf - XSTRING (object)->data;
3433 XSETFASTINT (zero, 0);
3434 #ifdef EMACS_HAS_USECS
3435 wait_reading_process_input (0, 20000, zero, 0);
3436 #else
3437 wait_reading_process_input (1, 0, zero, 0);
3438 #endif
3440 if (BUFFERP (object))
3441 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
3442 else if (STRINGP (object))
3443 buf = offset + XSTRING (object)->data;
3445 rv = 0;
3447 else
3448 /* This is a real error. */
3449 report_file_error ("writing to process", Fcons (proc, Qnil));
3451 buf += rv;
3452 len -= rv;
3453 this -= rv;
3456 /* If we sent just part of the string, put in an EOF
3457 to force it through, before we send the rest. */
3458 if (len > 0)
3459 Fprocess_send_eof (proc);
3461 #endif
3462 else
3464 XPROCESS (proc)->raw_status_low = Qnil;
3465 XPROCESS (proc)->raw_status_high = Qnil;
3466 XPROCESS (proc)->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
3467 XSETINT (XPROCESS (proc)->tick, ++process_tick);
3468 deactivate_process (proc);
3469 #ifdef VMS
3470 error ("Error writing to process %s; closed it", procname);
3471 #else
3472 error ("SIGPIPE raised on process %s; closed it", procname);
3473 #endif
3476 UNGCPRO;
3479 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
3480 3, 3, 0,
3481 "Send current contents of region as input to PROCESS.\n\
3482 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
3483 nil, indicating the current buffer's process.\n\
3484 Called from program, takes three arguments, PROCESS, START and END.\n\
3485 If the region is more than 500 characters long,\n\
3486 it is sent in several bunches. This may happen even for shorter regions.\n\
3487 Output from processes can arrive in between bunches.")
3488 (process, start, end)
3489 Lisp_Object process, start, end;
3491 Lisp_Object proc;
3492 int start1, end1;
3494 proc = get_process (process);
3495 validate_region (&start, &end);
3497 if (XINT (start) < GPT && XINT (end) > GPT)
3498 move_gap (XINT (start));
3500 start1 = CHAR_TO_BYTE (XINT (start));
3501 end1 = CHAR_TO_BYTE (XINT (end));
3502 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
3503 Fcurrent_buffer ());
3505 return Qnil;
3508 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
3509 2, 2, 0,
3510 "Send PROCESS the contents of STRING as input.\n\
3511 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
3512 nil, indicating the current buffer's process.\n\
3513 If STRING is more than 500 characters long,\n\
3514 it is sent in several bunches. This may happen even for shorter strings.\n\
3515 Output from processes can arrive in between bunches.")
3516 (process, string)
3517 Lisp_Object process, string;
3519 Lisp_Object proc;
3520 CHECK_STRING (string, 1);
3521 proc = get_process (process);
3522 send_process (proc, XSTRING (string)->data,
3523 STRING_BYTES (XSTRING (string)), string);
3524 return Qnil;
3527 DEFUN ("process-running-child-p", Fprocess_running_child_p,
3528 Sprocess_running_child_p, 0, 1, 0,
3529 "Return t if PROCESS has given the terminal to a child.\n\
3530 If the operating system does not make it possible to find out,\n\
3531 return t unconditionally.")
3532 (process)
3533 Lisp_Object process;
3535 /* Initialize in case ioctl doesn't exist or gives an error,
3536 in a way that will cause returning t. */
3537 int gid = 0;
3538 Lisp_Object proc;
3539 struct Lisp_Process *p;
3541 proc = get_process (process);
3542 p = XPROCESS (proc);
3544 if (!EQ (p->childp, Qt))
3545 error ("Process %s is not a subprocess",
3546 XSTRING (p->name)->data);
3547 if (XINT (p->infd) < 0)
3548 error ("Process %s is not active",
3549 XSTRING (p->name)->data);
3551 #ifdef TIOCGPGRP
3552 if (!NILP (p->subtty))
3553 ioctl (XFASTINT (p->subtty), TIOCGPGRP, &gid);
3554 else
3555 ioctl (XINT (p->infd), TIOCGPGRP, &gid);
3556 #endif /* defined (TIOCGPGRP ) */
3558 if (gid == XFASTINT (p->pid))
3559 return Qnil;
3560 return Qt;
3563 /* send a signal number SIGNO to PROCESS.
3564 If CURRENT_GROUP is t, that means send to the process group
3565 that currently owns the terminal being used to communicate with PROCESS.
3566 This is used for various commands in shell mode.
3567 If CURRENT_GROUP is lambda, that means send to the process group
3568 that currently owns the terminal, but only if it is NOT the shell itself.
3570 If NOMSG is zero, insert signal-announcements into process's buffers
3571 right away.
3573 If we can, we try to signal PROCESS by sending control characters
3574 down the pty. This allows us to signal inferiors who have changed
3575 their uid, for which killpg would return an EPERM error. */
3577 static void
3578 process_send_signal (process, signo, current_group, nomsg)
3579 Lisp_Object process;
3580 int signo;
3581 Lisp_Object current_group;
3582 int nomsg;
3584 Lisp_Object proc;
3585 register struct Lisp_Process *p;
3586 int gid;
3587 int no_pgrp = 0;
3589 proc = get_process (process);
3590 p = XPROCESS (proc);
3592 if (!EQ (p->childp, Qt))
3593 error ("Process %s is not a subprocess",
3594 XSTRING (p->name)->data);
3595 if (XINT (p->infd) < 0)
3596 error ("Process %s is not active",
3597 XSTRING (p->name)->data);
3599 if (NILP (p->pty_flag))
3600 current_group = Qnil;
3602 /* If we are using pgrps, get a pgrp number and make it negative. */
3603 if (!NILP (current_group))
3605 #ifdef SIGNALS_VIA_CHARACTERS
3606 /* If possible, send signals to the entire pgrp
3607 by sending an input character to it. */
3609 /* TERMIOS is the latest and bestest, and seems most likely to
3610 work. If the system has it, use it. */
3611 #ifdef HAVE_TERMIOS
3612 struct termios t;
3614 switch (signo)
3616 case SIGINT:
3617 tcgetattr (XINT (p->infd), &t);
3618 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
3619 return;
3621 case SIGQUIT:
3622 tcgetattr (XINT (p->infd), &t);
3623 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
3624 return;
3626 case SIGTSTP:
3627 tcgetattr (XINT (p->infd), &t);
3628 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
3629 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
3630 #else
3631 send_process (proc, &t.c_cc[VSUSP], 1, Qnil);
3632 #endif
3633 return;
3636 #else /* ! HAVE_TERMIOS */
3638 /* On Berkeley descendants, the following IOCTL's retrieve the
3639 current control characters. */
3640 #if defined (TIOCGLTC) && defined (TIOCGETC)
3642 struct tchars c;
3643 struct ltchars lc;
3645 switch (signo)
3647 case SIGINT:
3648 ioctl (XINT (p->infd), TIOCGETC, &c);
3649 send_process (proc, &c.t_intrc, 1, Qnil);
3650 return;
3651 case SIGQUIT:
3652 ioctl (XINT (p->infd), TIOCGETC, &c);
3653 send_process (proc, &c.t_quitc, 1, Qnil);
3654 return;
3655 #ifdef SIGTSTP
3656 case SIGTSTP:
3657 ioctl (XINT (p->infd), TIOCGLTC, &lc);
3658 send_process (proc, &lc.t_suspc, 1, Qnil);
3659 return;
3660 #endif /* ! defined (SIGTSTP) */
3663 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
3665 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
3666 characters. */
3667 #ifdef TCGETA
3668 struct termio t;
3669 switch (signo)
3671 case SIGINT:
3672 ioctl (XINT (p->infd), TCGETA, &t);
3673 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
3674 return;
3675 case SIGQUIT:
3676 ioctl (XINT (p->infd), TCGETA, &t);
3677 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
3678 return;
3679 #ifdef SIGTSTP
3680 case SIGTSTP:
3681 ioctl (XINT (p->infd), TCGETA, &t);
3682 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
3683 return;
3684 #endif /* ! defined (SIGTSTP) */
3686 #else /* ! defined (TCGETA) */
3687 Your configuration files are messed up.
3688 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
3689 you'd better be using one of the alternatives above! */
3690 #endif /* ! defined (TCGETA) */
3691 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
3692 #endif /* ! defined HAVE_TERMIOS */
3693 #endif /* ! defined (SIGNALS_VIA_CHARACTERS) */
3695 #ifdef TIOCGPGRP
3696 /* Get the pgrp using the tty itself, if we have that.
3697 Otherwise, use the pty to get the pgrp.
3698 On pfa systems, saka@pfu.fujitsu.co.JP writes:
3699 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
3700 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
3701 His patch indicates that if TIOCGPGRP returns an error, then
3702 we should just assume that p->pid is also the process group id. */
3704 int err;
3706 if (!NILP (p->subtty))
3707 err = ioctl (XFASTINT (p->subtty), TIOCGPGRP, &gid);
3708 else
3709 err = ioctl (XINT (p->infd), TIOCGPGRP, &gid);
3711 #ifdef pfa
3712 if (err == -1)
3713 gid = - XFASTINT (p->pid);
3714 #endif /* ! defined (pfa) */
3716 if (gid == -1)
3717 no_pgrp = 1;
3718 else
3719 gid = - gid;
3720 #else /* ! defined (TIOCGPGRP ) */
3721 /* Can't select pgrps on this system, so we know that
3722 the child itself heads the pgrp. */
3723 gid = - XFASTINT (p->pid);
3724 #endif /* ! defined (TIOCGPGRP ) */
3726 /* If current_group is lambda, and the shell owns the terminal,
3727 don't send any signal. */
3728 if (EQ (current_group, Qlambda) && gid == - XFASTINT (p->pid))
3729 return;
3731 else
3732 gid = - XFASTINT (p->pid);
3734 switch (signo)
3736 #ifdef SIGCONT
3737 case SIGCONT:
3738 p->raw_status_low = Qnil;
3739 p->raw_status_high = Qnil;
3740 p->status = Qrun;
3741 XSETINT (p->tick, ++process_tick);
3742 if (!nomsg)
3743 status_notify ();
3744 break;
3745 #endif /* ! defined (SIGCONT) */
3746 case SIGINT:
3747 #ifdef VMS
3748 send_process (proc, "\003", 1, Qnil); /* ^C */
3749 goto whoosh;
3750 #endif
3751 case SIGQUIT:
3752 #ifdef VMS
3753 send_process (proc, "\031", 1, Qnil); /* ^Y */
3754 goto whoosh;
3755 #endif
3756 case SIGKILL:
3757 #ifdef VMS
3758 sys$forcex (&(XFASTINT (p->pid)), 0, 1);
3759 whoosh:
3760 #endif
3761 flush_pending_output (XINT (p->infd));
3762 break;
3765 /* If we don't have process groups, send the signal to the immediate
3766 subprocess. That isn't really right, but it's better than any
3767 obvious alternative. */
3768 if (no_pgrp)
3770 kill (XFASTINT (p->pid), signo);
3771 return;
3774 /* gid may be a pid, or minus a pgrp's number */
3775 #ifdef TIOCSIGSEND
3776 if (!NILP (current_group))
3777 ioctl (XINT (p->infd), TIOCSIGSEND, signo);
3778 else
3780 gid = - XFASTINT (p->pid);
3781 kill (gid, signo);
3783 #else /* ! defined (TIOCSIGSEND) */
3784 EMACS_KILLPG (-gid, signo);
3785 #endif /* ! defined (TIOCSIGSEND) */
3788 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
3789 "Interrupt process PROCESS.\n\
3790 PROCESS may be a process, a buffer, or the name of a process or buffer.\n\
3791 nil or no arg means current buffer's process.\n\
3792 Second arg CURRENT-GROUP non-nil means send signal to\n\
3793 the current process-group of the process's controlling terminal\n\
3794 rather than to the process's own process group.\n\
3795 If the process is a shell, this means interrupt current subjob\n\
3796 rather than the shell.\n\
3798 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,\n\
3799 don't send the signal.")
3800 (process, current_group)
3801 Lisp_Object process, current_group;
3803 process_send_signal (process, SIGINT, current_group, 0);
3804 return process;
3807 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
3808 "Kill process PROCESS. May be process or name of one.\n\
3809 See function `interrupt-process' for more details on usage.")
3810 (process, current_group)
3811 Lisp_Object process, current_group;
3813 process_send_signal (process, SIGKILL, current_group, 0);
3814 return process;
3817 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
3818 "Send QUIT signal to process PROCESS. May be process or name of one.\n\
3819 See function `interrupt-process' for more details on usage.")
3820 (process, current_group)
3821 Lisp_Object process, current_group;
3823 process_send_signal (process, SIGQUIT, current_group, 0);
3824 return process;
3827 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
3828 "Stop process PROCESS. May be process or name of one.\n\
3829 See function `interrupt-process' for more details on usage.")
3830 (process, current_group)
3831 Lisp_Object process, current_group;
3833 #ifndef SIGTSTP
3834 error ("no SIGTSTP support");
3835 #else
3836 process_send_signal (process, SIGTSTP, current_group, 0);
3837 #endif
3838 return process;
3841 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
3842 "Continue process PROCESS. May be process or name of one.\n\
3843 See function `interrupt-process' for more details on usage.")
3844 (process, current_group)
3845 Lisp_Object process, current_group;
3847 #ifdef SIGCONT
3848 process_send_signal (process, SIGCONT, current_group, 0);
3849 #else
3850 error ("no SIGCONT support");
3851 #endif
3852 return process;
3855 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
3856 2, 2, "nProcess number: \nnSignal code: ",
3857 "Send the process with process id PID the signal with code SIGCODE.\n\
3858 PID must be an integer. The process need not be a child of this Emacs.\n\
3859 SIGCODE may be an integer, or a symbol whose name is a signal name.")
3860 (pid, sigcode)
3861 Lisp_Object pid, sigcode;
3863 CHECK_NUMBER (pid, 0);
3865 #define handle_signal(NAME, VALUE) \
3866 else if (!strcmp (name, NAME)) \
3867 XSETINT (sigcode, VALUE)
3869 if (INTEGERP (sigcode))
3871 else
3873 unsigned char *name;
3875 CHECK_SYMBOL (sigcode, 1);
3876 name = XSYMBOL (sigcode)->name->data;
3878 if (0)
3880 #ifdef SIGHUP
3881 handle_signal ("SIGHUP", SIGHUP);
3882 #endif
3883 #ifdef SIGINT
3884 handle_signal ("SIGINT", SIGINT);
3885 #endif
3886 #ifdef SIGQUIT
3887 handle_signal ("SIGQUIT", SIGQUIT);
3888 #endif
3889 #ifdef SIGILL
3890 handle_signal ("SIGILL", SIGILL);
3891 #endif
3892 #ifdef SIGABRT
3893 handle_signal ("SIGABRT", SIGABRT);
3894 #endif
3895 #ifdef SIGEMT
3896 handle_signal ("SIGEMT", SIGEMT);
3897 #endif
3898 #ifdef SIGKILL
3899 handle_signal ("SIGKILL", SIGKILL);
3900 #endif
3901 #ifdef SIGFPE
3902 handle_signal ("SIGFPE", SIGFPE);
3903 #endif
3904 #ifdef SIGBUS
3905 handle_signal ("SIGBUS", SIGBUS);
3906 #endif
3907 #ifdef SIGSEGV
3908 handle_signal ("SIGSEGV", SIGSEGV);
3909 #endif
3910 #ifdef SIGSYS
3911 handle_signal ("SIGSYS", SIGSYS);
3912 #endif
3913 #ifdef SIGPIPE
3914 handle_signal ("SIGPIPE", SIGPIPE);
3915 #endif
3916 #ifdef SIGALRM
3917 handle_signal ("SIGALRM", SIGALRM);
3918 #endif
3919 #ifdef SIGTERM
3920 handle_signal ("SIGTERM", SIGTERM);
3921 #endif
3922 #ifdef SIGURG
3923 handle_signal ("SIGURG", SIGURG);
3924 #endif
3925 #ifdef SIGSTOP
3926 handle_signal ("SIGSTOP", SIGSTOP);
3927 #endif
3928 #ifdef SIGTSTP
3929 handle_signal ("SIGTSTP", SIGTSTP);
3930 #endif
3931 #ifdef SIGCONT
3932 handle_signal ("SIGCONT", SIGCONT);
3933 #endif
3934 #ifdef SIGCHLD
3935 handle_signal ("SIGCHLD", SIGCHLD);
3936 #endif
3937 #ifdef SIGTTIN
3938 handle_signal ("SIGTTIN", SIGTTIN);
3939 #endif
3940 #ifdef SIGTTOU
3941 handle_signal ("SIGTTOU", SIGTTOU);
3942 #endif
3943 #ifdef SIGIO
3944 handle_signal ("SIGIO", SIGIO);
3945 #endif
3946 #ifdef SIGXCPU
3947 handle_signal ("SIGXCPU", SIGXCPU);
3948 #endif
3949 #ifdef SIGXFSZ
3950 handle_signal ("SIGXFSZ", SIGXFSZ);
3951 #endif
3952 #ifdef SIGVTALRM
3953 handle_signal ("SIGVTALRM", SIGVTALRM);
3954 #endif
3955 #ifdef SIGPROF
3956 handle_signal ("SIGPROF", SIGPROF);
3957 #endif
3958 #ifdef SIGWINCH
3959 handle_signal ("SIGWINCH", SIGWINCH);
3960 #endif
3961 #ifdef SIGINFO
3962 handle_signal ("SIGINFO", SIGINFO);
3963 #endif
3964 #ifdef SIGUSR1
3965 handle_signal ("SIGUSR1", SIGUSR1);
3966 #endif
3967 #ifdef SIGUSR2
3968 handle_signal ("SIGUSR2", SIGUSR2);
3969 #endif
3970 else
3971 error ("Undefined signal name %s", name);
3974 #undef handle_signal
3976 return make_number (kill (XINT (pid), XINT (sigcode)));
3979 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
3980 "Make PROCESS see end-of-file in its input.\n\
3981 EOF comes after any text already sent to it.\n\
3982 PROCESS may be a process, a buffer, the name of a process or buffer, or\n\
3983 nil, indicating the current buffer's process.\n\
3984 If PROCESS is a network connection, or is a process communicating\n\
3985 through a pipe (as opposed to a pty), then you cannot send any more\n\
3986 text to PROCESS after you call this function.")
3987 (process)
3988 Lisp_Object process;
3990 Lisp_Object proc;
3991 struct coding_system *coding;
3993 proc = get_process (process);
3994 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
3996 /* Make sure the process is really alive. */
3997 if (! NILP (XPROCESS (proc)->raw_status_low))
3998 update_status (XPROCESS (proc));
3999 if (! EQ (XPROCESS (proc)->status, Qrun))
4000 error ("Process %s not running", XSTRING (XPROCESS (proc)->name)->data);
4002 if (CODING_REQUIRE_FLUSHING (coding))
4004 coding->mode |= CODING_MODE_LAST_BLOCK;
4005 send_process (proc, "", 0, Qnil);
4008 #ifdef VMS
4009 send_process (proc, "\032", 1, Qnil); /* ^z */
4010 #else
4011 if (!NILP (XPROCESS (proc)->pty_flag))
4012 send_process (proc, "\004", 1, Qnil);
4013 else
4015 int old_outfd, new_outfd;
4017 #ifdef HAVE_SHUTDOWN
4018 /* If this is a network connection, or socketpair is used
4019 for communication with the subprocess, call shutdown to cause EOF.
4020 (In some old system, shutdown to socketpair doesn't work.
4021 Then we just can't win.) */
4022 if (NILP (XPROCESS (proc)->pid)
4023 || XINT (XPROCESS (proc)->outfd) == XINT (XPROCESS (proc)->infd))
4024 shutdown (XINT (XPROCESS (proc)->outfd), 1);
4025 /* In case of socketpair, outfd == infd, so don't close it. */
4026 if (XINT (XPROCESS (proc)->outfd) != XINT (XPROCESS (proc)->infd))
4027 emacs_close (XINT (XPROCESS (proc)->outfd));
4028 #else /* not HAVE_SHUTDOWN */
4029 emacs_close (XINT (XPROCESS (proc)->outfd));
4030 #endif /* not HAVE_SHUTDOWN */
4031 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
4032 old_outfd = XINT (XPROCESS (proc)->outfd);
4034 if (!proc_encode_coding_system[new_outfd])
4035 proc_encode_coding_system[new_outfd]
4036 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
4037 bcopy (proc_encode_coding_system[old_outfd],
4038 proc_encode_coding_system[new_outfd],
4039 sizeof (struct coding_system));
4040 bzero (proc_encode_coding_system[old_outfd],
4041 sizeof (struct coding_system));
4043 XSETINT (XPROCESS (proc)->outfd, new_outfd);
4045 #endif /* VMS */
4046 return process;
4049 /* Kill all processes associated with `buffer'.
4050 If `buffer' is nil, kill all processes */
4052 void
4053 kill_buffer_processes (buffer)
4054 Lisp_Object buffer;
4056 Lisp_Object tail, proc;
4058 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
4060 proc = XCDR (XCAR (tail));
4061 if (GC_PROCESSP (proc)
4062 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
4064 if (NETCONN_P (proc))
4065 Fdelete_process (proc);
4066 else if (XINT (XPROCESS (proc)->infd) >= 0)
4067 process_send_signal (proc, SIGHUP, Qnil, 1);
4072 /* On receipt of a signal that a child status has changed,
4073 loop asking about children with changed statuses until
4074 the system says there are no more.
4075 All we do is change the status;
4076 we do not run sentinels or print notifications.
4077 That is saved for the next time keyboard input is done,
4078 in order to avoid timing errors. */
4080 /** WARNING: this can be called during garbage collection.
4081 Therefore, it must not be fooled by the presence of mark bits in
4082 Lisp objects. */
4084 /** USG WARNING: Although it is not obvious from the documentation
4085 in signal(2), on a USG system the SIGCLD handler MUST NOT call
4086 signal() before executing at least one wait(), otherwise the handler
4087 will be called again, resulting in an infinite loop. The relevant
4088 portion of the documentation reads "SIGCLD signals will be queued
4089 and the signal-catching function will be continually reentered until
4090 the queue is empty". Invoking signal() causes the kernel to reexamine
4091 the SIGCLD queue. Fred Fish, UniSoft Systems Inc. */
4093 SIGTYPE
4094 sigchld_handler (signo)
4095 int signo;
4097 int old_errno = errno;
4098 Lisp_Object proc;
4099 register struct Lisp_Process *p;
4100 extern EMACS_TIME *input_available_clear_time;
4102 #ifdef BSD4_1
4103 extern int sigheld;
4104 sigheld |= sigbit (SIGCHLD);
4105 #endif
4107 while (1)
4109 register int pid;
4110 WAITTYPE w;
4111 Lisp_Object tail;
4113 #ifdef WNOHANG
4114 #ifndef WUNTRACED
4115 #define WUNTRACED 0
4116 #endif /* no WUNTRACED */
4117 /* Keep trying to get a status until we get a definitive result. */
4120 errno = 0;
4121 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
4123 while (pid <= 0 && errno == EINTR);
4125 if (pid <= 0)
4127 /* A real failure. We have done all our job, so return. */
4129 /* USG systems forget handlers when they are used;
4130 must reestablish each time */
4131 #if defined (USG) && !defined (POSIX_SIGNALS)
4132 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
4133 #endif
4134 #ifdef BSD4_1
4135 sigheld &= ~sigbit (SIGCHLD);
4136 sigrelse (SIGCHLD);
4137 #endif
4138 errno = old_errno;
4139 return;
4141 #else
4142 pid = wait (&w);
4143 #endif /* no WNOHANG */
4145 /* Find the process that signaled us, and record its status. */
4147 p = 0;
4148 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
4150 proc = XCDR (XCAR (tail));
4151 p = XPROCESS (proc);
4152 if (EQ (p->childp, Qt) && XFASTINT (p->pid) == pid)
4153 break;
4154 p = 0;
4157 /* Look for an asynchronous process whose pid hasn't been filled
4158 in yet. */
4159 if (p == 0)
4160 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
4162 proc = XCDR (XCAR (tail));
4163 p = XPROCESS (proc);
4164 if (INTEGERP (p->pid) && XINT (p->pid) == -1)
4165 break;
4166 p = 0;
4169 /* Change the status of the process that was found. */
4170 if (p != 0)
4172 union { int i; WAITTYPE wt; } u;
4173 int clear_desc_flag = 0;
4175 XSETINT (p->tick, ++process_tick);
4176 u.wt = w;
4177 XSETINT (p->raw_status_low, u.i & 0xffff);
4178 XSETINT (p->raw_status_high, u.i >> 16);
4180 /* If process has terminated, stop waiting for its output. */
4181 if ((WIFSIGNALED (w) || WIFEXITED (w))
4182 && XINT (p->infd) >= 0)
4183 clear_desc_flag = 1;
4185 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
4186 if (clear_desc_flag)
4188 FD_CLR (XINT (p->infd), &input_wait_mask);
4189 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
4192 /* Tell wait_reading_process_input that it needs to wake up and
4193 look around. */
4194 if (input_available_clear_time)
4195 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
4198 /* There was no asynchronous process found for that id. Check
4199 if we have a synchronous process. */
4200 else
4202 synch_process_alive = 0;
4204 /* Report the status of the synchronous process. */
4205 if (WIFEXITED (w))
4206 synch_process_retcode = WRETCODE (w);
4207 else if (WIFSIGNALED (w))
4209 int code = WTERMSIG (w);
4210 char *signame;
4212 synchronize_system_messages_locale ();
4213 signame = strsignal (code);
4215 if (signame == 0)
4216 signame = "unknown";
4218 synch_process_death = signame;
4221 /* Tell wait_reading_process_input that it needs to wake up and
4222 look around. */
4223 if (input_available_clear_time)
4224 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
4227 /* On some systems, we must return right away.
4228 If any more processes want to signal us, we will
4229 get another signal.
4230 Otherwise (on systems that have WNOHANG), loop around
4231 to use up all the processes that have something to tell us. */
4232 #if defined (USG) && ! (defined (HPUX) && defined (WNOHANG)) || defined (WINDOWSNT)
4233 #if defined (USG) && ! defined (POSIX_SIGNALS)
4234 signal (signo, sigchld_handler);
4235 #endif
4236 errno = old_errno;
4237 return;
4238 #endif /* USG, but not HPUX with WNOHANG */
4243 static Lisp_Object
4244 exec_sentinel_unwind (data)
4245 Lisp_Object data;
4247 XPROCESS (XCAR (data))->sentinel = XCDR (data);
4248 return Qnil;
4251 static Lisp_Object
4252 exec_sentinel_error_handler (error)
4253 Lisp_Object error;
4255 cmd_error_internal (error, "error in process sentinel: ");
4256 Vinhibit_quit = Qt;
4257 update_echo_area ();
4258 Fsleep_for (make_number (2), Qnil);
4261 static void
4262 exec_sentinel (proc, reason)
4263 Lisp_Object proc, reason;
4265 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
4266 register struct Lisp_Process *p = XPROCESS (proc);
4267 int count = specpdl_ptr - specpdl;
4268 int outer_running_asynch_code = running_asynch_code;
4269 int waiting = waiting_for_user_input_p;
4271 /* No need to gcpro these, because all we do with them later
4272 is test them for EQness, and none of them should be a string. */
4273 odeactivate = Vdeactivate_mark;
4274 XSETBUFFER (obuffer, current_buffer);
4275 okeymap = current_buffer->keymap;
4277 sentinel = p->sentinel;
4278 if (NILP (sentinel))
4279 return;
4281 /* Zilch the sentinel while it's running, to avoid recursive invocations;
4282 assure that it gets restored no matter how the sentinel exits. */
4283 p->sentinel = Qnil;
4284 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
4285 /* Inhibit quit so that random quits don't screw up a running filter. */
4286 specbind (Qinhibit_quit, Qt);
4287 specbind (Qlast_nonmenu_event, Qt);
4289 /* In case we get recursively called,
4290 and we already saved the match data nonrecursively,
4291 save the same match data in safely recursive fashion. */
4292 if (outer_running_asynch_code)
4294 Lisp_Object tem;
4295 tem = Fmatch_data (Qnil, Qnil);
4296 restore_match_data ();
4297 record_unwind_protect (Fset_match_data, Fmatch_data (Qnil, Qnil));
4298 Fset_match_data (tem);
4301 /* For speed, if a search happens within this code,
4302 save the match data in a special nonrecursive fashion. */
4303 running_asynch_code = 1;
4305 internal_condition_case_1 (read_process_output_call,
4306 Fcons (sentinel,
4307 Fcons (proc, Fcons (reason, Qnil))),
4308 !NILP (Vdebug_on_error) ? Qnil : Qerror,
4309 exec_sentinel_error_handler);
4311 /* If we saved the match data nonrecursively, restore it now. */
4312 restore_match_data ();
4313 running_asynch_code = outer_running_asynch_code;
4315 Vdeactivate_mark = odeactivate;
4317 /* Restore waiting_for_user_input_p as it was
4318 when we were called, in case the filter clobbered it. */
4319 waiting_for_user_input_p = waiting;
4321 #if 0
4322 if (! EQ (Fcurrent_buffer (), obuffer)
4323 || ! EQ (current_buffer->keymap, okeymap))
4324 #endif
4325 /* But do it only if the caller is actually going to read events.
4326 Otherwise there's no need to make him wake up, and it could
4327 cause trouble (for example it would make Fsit_for return). */
4328 if (waiting_for_user_input_p == -1)
4329 record_asynch_buffer_change ();
4331 unbind_to (count, Qnil);
4334 /* Report all recent events of a change in process status
4335 (either run the sentinel or output a message).
4336 This is done while Emacs is waiting for keyboard input. */
4338 void
4339 status_notify ()
4341 register Lisp_Object proc, buffer;
4342 Lisp_Object tail, msg;
4343 struct gcpro gcpro1, gcpro2;
4345 tail = Qnil;
4346 msg = Qnil;
4347 /* We need to gcpro tail; if read_process_output calls a filter
4348 which deletes a process and removes the cons to which tail points
4349 from Vprocess_alist, and then causes a GC, tail is an unprotected
4350 reference. */
4351 GCPRO2 (tail, msg);
4353 /* Set this now, so that if new processes are created by sentinels
4354 that we run, we get called again to handle their status changes. */
4355 update_tick = process_tick;
4357 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
4359 Lisp_Object symbol;
4360 register struct Lisp_Process *p;
4362 proc = Fcdr (Fcar (tail));
4363 p = XPROCESS (proc);
4365 if (XINT (p->tick) != XINT (p->update_tick))
4367 XSETINT (p->update_tick, XINT (p->tick));
4369 /* If process is still active, read any output that remains. */
4370 while (! EQ (p->filter, Qt)
4371 && XINT (p->infd) >= 0
4372 && read_process_output (proc, XINT (p->infd)) > 0);
4374 buffer = p->buffer;
4376 /* Get the text to use for the message. */
4377 if (!NILP (p->raw_status_low))
4378 update_status (p);
4379 msg = status_message (p->status);
4381 /* If process is terminated, deactivate it or delete it. */
4382 symbol = p->status;
4383 if (CONSP (p->status))
4384 symbol = XCAR (p->status);
4386 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
4387 || EQ (symbol, Qclosed))
4389 if (delete_exited_processes)
4390 remove_process (proc);
4391 else
4392 deactivate_process (proc);
4395 /* The actions above may have further incremented p->tick.
4396 So set p->update_tick again
4397 so that an error in the sentinel will not cause
4398 this code to be run again. */
4399 XSETINT (p->update_tick, XINT (p->tick));
4400 /* Now output the message suitably. */
4401 if (!NILP (p->sentinel))
4402 exec_sentinel (proc, msg);
4403 /* Don't bother with a message in the buffer
4404 when a process becomes runnable. */
4405 else if (!EQ (symbol, Qrun) && !NILP (buffer))
4407 Lisp_Object ro, tem;
4408 struct buffer *old = current_buffer;
4409 int opoint, opoint_byte;
4410 int before, before_byte;
4412 ro = XBUFFER (buffer)->read_only;
4414 /* Avoid error if buffer is deleted
4415 (probably that's why the process is dead, too) */
4416 if (NILP (XBUFFER (buffer)->name))
4417 continue;
4418 Fset_buffer (buffer);
4420 opoint = PT;
4421 opoint_byte = PT_BYTE;
4422 /* Insert new output into buffer
4423 at the current end-of-output marker,
4424 thus preserving logical ordering of input and output. */
4425 if (XMARKER (p->mark)->buffer)
4426 Fgoto_char (p->mark);
4427 else
4428 SET_PT_BOTH (ZV, ZV_BYTE);
4430 before = PT;
4431 before_byte = PT_BYTE;
4433 tem = current_buffer->read_only;
4434 current_buffer->read_only = Qnil;
4435 insert_string ("\nProcess ");
4436 Finsert (1, &p->name);
4437 insert_string (" ");
4438 Finsert (1, &msg);
4439 current_buffer->read_only = tem;
4440 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
4442 if (opoint >= before)
4443 SET_PT_BOTH (opoint + (PT - before),
4444 opoint_byte + (PT_BYTE - before_byte));
4445 else
4446 SET_PT_BOTH (opoint, opoint_byte);
4448 set_buffer_internal (old);
4451 } /* end for */
4453 update_mode_lines++; /* in case buffers use %s in mode-line-format */
4454 redisplay_preserve_echo_area ();
4456 UNGCPRO;
4460 DEFUN ("set-process-coding-system", Fset_process_coding_system,
4461 Sset_process_coding_system, 1, 3, 0,
4462 "Set coding systems of PROCESS to DECODING and ENCODING.\n\
4463 DECODING will be used to decode subprocess output and ENCODING to\n\
4464 encode subprocess input.")
4465 (proc, decoding, encoding)
4466 register Lisp_Object proc, decoding, encoding;
4468 register struct Lisp_Process *p;
4470 CHECK_PROCESS (proc, 0);
4471 p = XPROCESS (proc);
4472 if (XINT (p->infd) < 0)
4473 error ("Input file descriptor of %s closed", XSTRING (p->name)->data);
4474 if (XINT (p->outfd) < 0)
4475 error ("Output file descriptor of %s closed", XSTRING (p->name)->data);
4477 p->decode_coding_system = Fcheck_coding_system (decoding);
4478 p->encode_coding_system = Fcheck_coding_system (encoding);
4479 setup_coding_system (decoding,
4480 proc_decode_coding_system[XINT (p->infd)]);
4481 setup_coding_system (encoding,
4482 proc_encode_coding_system[XINT (p->outfd)]);
4484 return Qnil;
4487 DEFUN ("process-coding-system",
4488 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
4489 "Return a cons of coding systems for decoding and encoding of PROCESS.")
4490 (proc)
4491 register Lisp_Object proc;
4493 CHECK_PROCESS (proc, 0);
4494 return Fcons (XPROCESS (proc)->decode_coding_system,
4495 XPROCESS (proc)->encode_coding_system);
4498 /* The first time this is called, assume keyboard input comes from DESC
4499 instead of from where we used to expect it.
4500 Subsequent calls mean assume input keyboard can come from DESC
4501 in addition to other places. */
4503 static int add_keyboard_wait_descriptor_called_flag;
4505 void
4506 add_keyboard_wait_descriptor (desc)
4507 int desc;
4509 if (! add_keyboard_wait_descriptor_called_flag)
4510 FD_CLR (0, &input_wait_mask);
4511 add_keyboard_wait_descriptor_called_flag = 1;
4512 FD_SET (desc, &input_wait_mask);
4513 FD_SET (desc, &non_process_wait_mask);
4514 if (desc > max_keyboard_desc)
4515 max_keyboard_desc = desc;
4518 /* From now on, do not expect DESC to give keyboard input. */
4520 void
4521 delete_keyboard_wait_descriptor (desc)
4522 int desc;
4524 int fd;
4525 int lim = max_keyboard_desc;
4527 FD_CLR (desc, &input_wait_mask);
4528 FD_CLR (desc, &non_process_wait_mask);
4530 if (desc == max_keyboard_desc)
4531 for (fd = 0; fd < lim; fd++)
4532 if (FD_ISSET (fd, &input_wait_mask)
4533 && !FD_ISSET (fd, &non_keyboard_wait_mask))
4534 max_keyboard_desc = fd;
4537 /* Return nonzero if *MASK has a bit set
4538 that corresponds to one of the keyboard input descriptors. */
4541 keyboard_bit_set (mask)
4542 SELECT_TYPE *mask;
4544 int fd;
4546 for (fd = 0; fd <= max_keyboard_desc; fd++)
4547 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
4548 && !FD_ISSET (fd, &non_keyboard_wait_mask))
4549 return 1;
4551 return 0;
4554 void
4555 init_process ()
4557 register int i;
4559 #ifdef SIGCHLD
4560 #ifndef CANNOT_DUMP
4561 if (! noninteractive || initialized)
4562 #endif
4563 signal (SIGCHLD, sigchld_handler);
4564 #endif
4566 FD_ZERO (&input_wait_mask);
4567 FD_ZERO (&non_keyboard_wait_mask);
4568 FD_ZERO (&non_process_wait_mask);
4569 max_process_desc = 0;
4571 FD_SET (0, &input_wait_mask);
4573 Vprocess_alist = Qnil;
4574 for (i = 0; i < MAXDESC; i++)
4576 chan_process[i] = Qnil;
4577 proc_buffered_char[i] = -1;
4579 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
4580 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
4582 Vdefault_process_coding_system
4583 = (NILP (buffer_defaults.enable_multibyte_characters)
4584 ? Fcons (Qraw_text, Qnil)
4585 : Fcons (Qemacs_mule, Qnil));
4588 void
4589 syms_of_process ()
4591 Qprocessp = intern ("processp");
4592 staticpro (&Qprocessp);
4593 Qrun = intern ("run");
4594 staticpro (&Qrun);
4595 Qstop = intern ("stop");
4596 staticpro (&Qstop);
4597 Qsignal = intern ("signal");
4598 staticpro (&Qsignal);
4600 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
4601 here again.
4603 Qexit = intern ("exit");
4604 staticpro (&Qexit); */
4606 Qopen = intern ("open");
4607 staticpro (&Qopen);
4608 Qclosed = intern ("closed");
4609 staticpro (&Qclosed);
4611 Qlast_nonmenu_event = intern ("last-nonmenu-event");
4612 staticpro (&Qlast_nonmenu_event);
4614 staticpro (&Vprocess_alist);
4616 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
4617 "*Non-nil means delete processes immediately when they exit.\n\
4618 nil means don't delete them until `list-processes' is run.");
4620 delete_exited_processes = 1;
4622 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
4623 "Control type of device used to communicate with subprocesses.\n\
4624 Values are nil to use a pipe, or t or `pty' to use a pty.\n\
4625 The value has no effect if the system has no ptys or if all ptys are busy:\n\
4626 then a pipe is used in any case.\n\
4627 The value takes effect when `start-process' is called.");
4628 Vprocess_connection_type = Qt;
4630 defsubr (&Sprocessp);
4631 defsubr (&Sget_process);
4632 defsubr (&Sget_buffer_process);
4633 defsubr (&Sdelete_process);
4634 defsubr (&Sprocess_status);
4635 defsubr (&Sprocess_exit_status);
4636 defsubr (&Sprocess_id);
4637 defsubr (&Sprocess_name);
4638 defsubr (&Sprocess_tty_name);
4639 defsubr (&Sprocess_command);
4640 defsubr (&Sset_process_buffer);
4641 defsubr (&Sprocess_buffer);
4642 defsubr (&Sprocess_mark);
4643 defsubr (&Sset_process_filter);
4644 defsubr (&Sprocess_filter);
4645 defsubr (&Sset_process_sentinel);
4646 defsubr (&Sprocess_sentinel);
4647 defsubr (&Sset_process_window_size);
4648 defsubr (&Sset_process_inherit_coding_system_flag);
4649 defsubr (&Sprocess_inherit_coding_system_flag);
4650 defsubr (&Sprocess_kill_without_query);
4651 defsubr (&Sprocess_contact);
4652 defsubr (&Slist_processes);
4653 defsubr (&Sprocess_list);
4654 defsubr (&Sstart_process);
4655 #ifdef HAVE_SOCKETS
4656 defsubr (&Sopen_network_stream);
4657 #endif /* HAVE_SOCKETS */
4658 defsubr (&Saccept_process_output);
4659 defsubr (&Sprocess_send_region);
4660 defsubr (&Sprocess_send_string);
4661 defsubr (&Sinterrupt_process);
4662 defsubr (&Skill_process);
4663 defsubr (&Squit_process);
4664 defsubr (&Sstop_process);
4665 defsubr (&Scontinue_process);
4666 defsubr (&Sprocess_running_child_p);
4667 defsubr (&Sprocess_send_eof);
4668 defsubr (&Ssignal_process);
4669 defsubr (&Swaiting_for_user_input_p);
4670 /* defsubr (&Sprocess_connection); */
4671 defsubr (&Sset_process_coding_system);
4672 defsubr (&Sprocess_coding_system);
4676 #else /* not subprocesses */
4678 #include <sys/types.h>
4679 #include <errno.h>
4681 #include "lisp.h"
4682 #include "systime.h"
4683 #include "charset.h"
4684 #include "coding.h"
4685 #include "termopts.h"
4686 #include "sysselect.h"
4688 extern int frame_garbaged;
4690 extern EMACS_TIME timer_check ();
4691 extern int timers_run;
4693 /* As described above, except assuming that there are no subprocesses:
4695 Wait for timeout to elapse and/or keyboard input to be available.
4697 time_limit is:
4698 timeout in seconds, or
4699 zero for no limit, or
4700 -1 means gobble data immediately available but don't wait for any.
4702 read_kbd is a Lisp_Object:
4703 0 to ignore keyboard input, or
4704 1 to return when input is available, or
4705 -1 means caller will actually read the input, so don't throw to
4706 the quit handler.
4707 a cons cell, meaning wait until its car is non-nil
4708 (and gobble terminal input into the buffer if any arrives), or
4709 We know that read_kbd will never be a Lisp_Process, since
4710 `subprocesses' isn't defined.
4712 do_display != 0 means redisplay should be done to show subprocess
4713 output that arrives.
4715 Return true iff we received input from any process. */
4718 wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
4719 int time_limit, microsecs;
4720 Lisp_Object read_kbd;
4721 int do_display;
4723 register int nfds;
4724 EMACS_TIME end_time, timeout;
4725 SELECT_TYPE waitchannels;
4726 int xerrno;
4727 Lisp_Object *wait_for_cell = 0;
4729 /* If waiting for non-nil in a cell, record where. */
4730 if (CONSP (read_kbd))
4732 wait_for_cell = &XCAR (read_kbd);
4733 XSETFASTINT (read_kbd, 0);
4736 /* What does time_limit really mean? */
4737 if (time_limit || microsecs)
4739 EMACS_GET_TIME (end_time);
4740 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4741 EMACS_ADD_TIME (end_time, end_time, timeout);
4744 /* Turn off periodic alarms (in case they are in use)
4745 because the select emulator uses alarms. */
4746 stop_polling ();
4748 while (1)
4750 int timeout_reduced_for_timers = 0;
4752 /* If calling from keyboard input, do not quit
4753 since we want to return C-g as an input character.
4754 Otherwise, do pending quit if requested. */
4755 if (XINT (read_kbd) >= 0)
4756 QUIT;
4758 /* Exit now if the cell we're waiting for became non-nil. */
4759 if (wait_for_cell && ! NILP (*wait_for_cell))
4760 break;
4762 /* Compute time from now till when time limit is up */
4763 /* Exit if already run out */
4764 if (time_limit == -1)
4766 /* -1 specified for timeout means
4767 gobble output available now
4768 but don't wait at all. */
4770 EMACS_SET_SECS_USECS (timeout, 0, 0);
4772 else if (time_limit || microsecs)
4774 EMACS_GET_TIME (timeout);
4775 EMACS_SUB_TIME (timeout, end_time, timeout);
4776 if (EMACS_TIME_NEG_P (timeout))
4777 break;
4779 else
4781 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4784 /* If our caller will not immediately handle keyboard events,
4785 run timer events directly.
4786 (Callers that will immediately read keyboard events
4787 call timer_delay on their own.) */
4788 if (! wait_for_cell)
4790 EMACS_TIME timer_delay;
4791 int old_timers_run;
4793 retry:
4794 old_timers_run = timers_run;
4795 timer_delay = timer_check (1);
4796 if (timers_run != old_timers_run && do_display)
4798 redisplay_preserve_echo_area ();
4799 /* We must retry, since a timer may have requeued itself
4800 and that could alter the time delay. */
4801 goto retry;
4804 /* If there is unread keyboard input, also return. */
4805 if (XINT (read_kbd) != 0
4806 && requeued_events_pending_p ())
4807 break;
4809 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4811 EMACS_TIME difference;
4812 EMACS_SUB_TIME (difference, timer_delay, timeout);
4813 if (EMACS_TIME_NEG_P (difference))
4815 timeout = timer_delay;
4816 timeout_reduced_for_timers = 1;
4821 /* Cause C-g and alarm signals to take immediate action,
4822 and cause input available signals to zero out timeout. */
4823 if (XINT (read_kbd) < 0)
4824 set_waiting_for_input (&timeout);
4826 /* Wait till there is something to do. */
4828 if (! XINT (read_kbd) && wait_for_cell == 0)
4829 FD_ZERO (&waitchannels);
4830 else
4831 FD_SET (0, &waitchannels);
4833 /* If a frame has been newly mapped and needs updating,
4834 reprocess its display stuff. */
4835 if (frame_garbaged && do_display)
4837 clear_waiting_for_input ();
4838 redisplay_preserve_echo_area ();
4839 if (XINT (read_kbd) < 0)
4840 set_waiting_for_input (&timeout);
4843 if (XINT (read_kbd) && detect_input_pending ())
4845 nfds = 0;
4846 FD_ZERO (&waitchannels);
4848 else
4849 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
4850 &timeout);
4852 xerrno = errno;
4854 /* Make C-g and alarm signals set flags again */
4855 clear_waiting_for_input ();
4857 /* If we woke up due to SIGWINCH, actually change size now. */
4858 do_pending_window_change (0);
4860 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4861 /* We waited the full specified time, so return now. */
4862 break;
4864 if (nfds == -1)
4866 /* If the system call was interrupted, then go around the
4867 loop again. */
4868 if (xerrno == EINTR)
4869 FD_ZERO (&waitchannels);
4870 else
4871 error ("select error: %s", emacs_strerror (xerrno));
4873 #ifdef sun
4874 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
4875 /* System sometimes fails to deliver SIGIO. */
4876 kill (getpid (), SIGIO);
4877 #endif
4878 #ifdef SIGIO
4879 if (XINT (read_kbd) && interrupt_input && (waitchannels & 1))
4880 kill (getpid (), SIGIO);
4881 #endif
4883 /* Check for keyboard input */
4885 if ((XINT (read_kbd) != 0)
4886 && detect_input_pending_run_timers (do_display))
4888 swallow_events (do_display);
4889 if (detect_input_pending_run_timers (do_display))
4890 break;
4893 /* If there is unread keyboard input, also return. */
4894 if (XINT (read_kbd) != 0
4895 && requeued_events_pending_p ())
4896 break;
4898 /* If wait_for_cell. check for keyboard input
4899 but don't run any timers.
4900 ??? (It seems wrong to me to check for keyboard
4901 input at all when wait_for_cell, but the code
4902 has been this way since July 1994.
4903 Try changing this after version 19.31.) */
4904 if (wait_for_cell
4905 && detect_input_pending ())
4907 swallow_events (do_display);
4908 if (detect_input_pending ())
4909 break;
4912 /* Exit now if the cell we're waiting for became non-nil. */
4913 if (wait_for_cell && ! NILP (*wait_for_cell))
4914 break;
4917 start_polling ();
4919 return 0;
4923 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
4924 /* Don't confuse make-docfile by having two doc strings for this function.
4925 make-docfile does not pay attention to #if, for good reason! */
4927 (name)
4928 register Lisp_Object name;
4930 return Qnil;
4933 DEFUN ("process-inherit-coding-system-flag",
4934 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
4935 1, 1, 0,
4936 /* Don't confuse make-docfile by having two doc strings for this function.
4937 make-docfile does not pay attention to #if, for good reason! */
4939 (process)
4940 register Lisp_Object process;
4942 /* Ignore the argument and return the value of
4943 inherit-process-coding-system. */
4944 return inherit_process_coding_system ? Qt : Qnil;
4947 /* Kill all processes associated with `buffer'.
4948 If `buffer' is nil, kill all processes.
4949 Since we have no subprocesses, this does nothing. */
4951 void
4952 kill_buffer_processes (buffer)
4953 Lisp_Object buffer;
4957 void
4958 init_process ()
4962 void
4963 syms_of_process ()
4965 defsubr (&Sget_buffer_process);
4966 defsubr (&Sprocess_inherit_coding_system_flag);
4970 #endif /* not subprocesses */