New misc type Lisp_Save_Value.
[emacs.git] / src / process.c
blob09b5270a1bd60c1d0d8e44ca7e97e650be99a25e
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 86, 87, 88, 93, 94, 95, 96, 98, 1999,
3 2001, 2002 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 #include <config.h>
24 #include <signal.h>
26 /* This file is split into two parts by the following preprocessor
27 conditional. The 'then' clause contains all of the support for
28 asynchronous subprocesses. The 'else' clause contains stub
29 versions of some of the asynchronous subprocess routines that are
30 often called elsewhere in Emacs, so we don't have to #ifdef the
31 sections that call them. */
34 #ifdef subprocesses
36 #include <stdio.h>
37 #include <errno.h>
38 #include <setjmp.h>
39 #include <sys/types.h> /* some typedefs are used in sys/file.h */
40 #include <sys/file.h>
41 #include <sys/stat.h>
42 #ifdef HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
46 #if defined(WINDOWSNT) || defined(UNIX98_PTYS)
47 #include <stdlib.h>
48 #include <fcntl.h>
49 #endif /* not WINDOWSNT */
51 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
52 #include <sys/socket.h>
53 #include <netdb.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #ifdef NEED_NET_ERRNO_H
57 #include <net/errno.h>
58 #endif /* NEED_NET_ERRNO_H */
60 /* Are local (unix) sockets supported? */
61 #if defined (HAVE_SYS_UN_H) && !defined (NO_SOCKETS_IN_FILE_SYSTEM)
62 #if !defined (AF_LOCAL) && defined (AF_UNIX)
63 #define AF_LOCAL AF_UNIX
64 #endif
65 #ifdef AF_LOCAL
66 #define HAVE_LOCAL_SOCKETS
67 #include <sys/un.h>
68 #endif
69 #endif
70 #endif /* HAVE_SOCKETS */
72 /* TERM is a poor-man's SLIP, used on GNU/Linux. */
73 #ifdef TERM
74 #include <client.h>
75 #endif
77 /* On some systems, e.g. DGUX, inet_addr returns a 'struct in_addr'. */
78 #ifdef HAVE_BROKEN_INET_ADDR
79 #define IN_ADDR struct in_addr
80 #define NUMERIC_ADDR_ERROR (numeric_addr.s_addr == -1)
81 #else
82 #define IN_ADDR unsigned long
83 #define NUMERIC_ADDR_ERROR (numeric_addr == -1)
84 #endif
86 #if defined(BSD_SYSTEM) || defined(STRIDE)
87 #include <sys/ioctl.h>
88 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
89 #include <fcntl.h>
90 #endif /* HAVE_PTYS and no O_NDELAY */
91 #endif /* BSD_SYSTEM || STRIDE */
93 #ifdef BROKEN_O_NONBLOCK
94 #undef O_NONBLOCK
95 #endif /* BROKEN_O_NONBLOCK */
97 #ifdef NEED_BSDTTY
98 #include <bsdtty.h>
99 #endif
101 #ifdef IRIS
102 #include <sys/sysmacros.h> /* for "minor" */
103 #endif /* not IRIS */
105 #ifdef HAVE_SYS_WAIT
106 #include <sys/wait.h>
107 #endif
109 #include "systime.h"
110 #include "systty.h"
112 #include "lisp.h"
113 #include "window.h"
114 #include "buffer.h"
115 #include "charset.h"
116 #include "coding.h"
117 #include "process.h"
118 #include "termhooks.h"
119 #include "termopts.h"
120 #include "commands.h"
121 #include "keyboard.h"
122 #include "frame.h"
123 #include "blockinput.h"
124 #include "dispextern.h"
125 #include "composite.h"
126 #include "atimer.h"
128 Lisp_Object Qprocessp;
129 Lisp_Object Qrun, Qstop, Qsignal;
130 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
131 Lisp_Object Qlocal, Qdatagram;
132 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
133 Lisp_Object QClocal, QCremote, QCcoding;
134 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
135 Lisp_Object QCsentinel, QClog, QCoptions;
136 Lisp_Object Qlast_nonmenu_event;
137 /* QCfamily is declared and initialized in xfaces.c,
138 QCfilter in keyboard.c. */
139 extern Lisp_Object QCfamily, QCfilter;
141 /* Qexit is declared and initialized in eval.c. */
143 /* QCfamily is defined in xfaces.c. */
144 extern Lisp_Object QCfamily;
145 /* QCfilter is defined in keyboard.c. */
146 extern Lisp_Object QCfilter;
148 /* a process object is a network connection when its childp field is neither
149 Qt nor Qnil but is instead a cons cell (HOSTNAME PORTNUM). */
151 #ifdef HAVE_SOCKETS
152 #define NETCONN_P(p) (GC_CONSP (XPROCESS (p)->childp))
153 #define NETCONN1_P(p) (GC_CONSP ((p)->childp))
154 #else
155 #define NETCONN_P(p) 0
156 #define NETCONN1_P(p) 0
157 #endif /* HAVE_SOCKETS */
159 /* Define first descriptor number available for subprocesses. */
160 #ifdef VMS
161 #define FIRST_PROC_DESC 1
162 #else /* Not VMS */
163 #define FIRST_PROC_DESC 3
164 #endif
166 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
167 testing SIGCHLD. */
169 #if !defined (SIGCHLD) && defined (SIGCLD)
170 #define SIGCHLD SIGCLD
171 #endif /* SIGCLD */
173 #include "syssignal.h"
175 #include "syswait.h"
177 extern void set_waiting_for_input P_ ((EMACS_TIME *));
179 #ifndef USE_CRT_DLL
180 extern int errno;
181 #endif
182 #ifdef VMS
183 extern char *sys_errlist[];
184 #endif
186 #ifndef HAVE_H_ERRNO
187 extern int h_errno;
188 #endif
190 /* t means use pty, nil means use a pipe,
191 maybe other values to come. */
192 static Lisp_Object Vprocess_connection_type;
194 #ifdef SKTPAIR
195 #ifndef HAVE_SOCKETS
196 #include <sys/socket.h>
197 #endif
198 #endif /* SKTPAIR */
200 /* These next two vars are non-static since sysdep.c uses them in the
201 emulation of `select'. */
202 /* Number of events of change of status of a process. */
203 int process_tick;
204 /* Number of events for which the user or sentinel has been notified. */
205 int update_tick;
207 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
209 #ifdef BROKEN_NON_BLOCKING_CONNECT
210 #undef NON_BLOCKING_CONNECT
211 #else
212 #ifndef NON_BLOCKING_CONNECT
213 #ifdef HAVE_SOCKETS
214 #ifdef HAVE_SELECT
215 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
216 #if defined (O_NONBLOCK) || defined (O_NDELAY)
217 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
218 #define NON_BLOCKING_CONNECT
219 #endif /* EWOULDBLOCK || EINPROGRESS */
220 #endif /* O_NONBLOCK || O_NDELAY */
221 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
222 #endif /* HAVE_SELECT */
223 #endif /* HAVE_SOCKETS */
224 #endif /* NON_BLOCKING_CONNECT */
225 #endif /* BROKEN_NON_BLOCKING_CONNECT */
227 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
228 this system. We need to read full packets, so we need a
229 "non-destructive" select. So we require either native select,
230 or emulation of select using FIONREAD. */
232 #ifdef BROKEN_DATAGRAM_SOCKETS
233 #undef DATAGRAM_SOCKETS
234 #else
235 #ifndef DATAGRAM_SOCKETS
236 #ifdef HAVE_SOCKETS
237 #if defined (HAVE_SELECT) || defined (FIONREAD)
238 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
239 #define DATAGRAM_SOCKETS
240 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
241 #endif /* HAVE_SELECT || FIONREAD */
242 #endif /* HAVE_SOCKETS */
243 #endif /* DATAGRAM_SOCKETS */
244 #endif /* BROKEN_DATAGRAM_SOCKETS */
246 #ifdef TERM
247 #undef NON_BLOCKING_CONNECT
248 #undef DATAGRAM_SOCKETS
249 #endif
252 #include "sysselect.h"
254 extern int keyboard_bit_set P_ ((SELECT_TYPE *));
256 /* If we support a window system, turn on the code to poll periodically
257 to detect C-g. It isn't actually used when doing interrupt input. */
258 #ifdef HAVE_WINDOW_SYSTEM
259 #define POLL_FOR_INPUT
260 #endif
262 /* Mask of bits indicating the descriptors that we wait for input on. */
264 static SELECT_TYPE input_wait_mask;
266 /* Mask that excludes keyboard input descriptor (s). */
268 static SELECT_TYPE non_keyboard_wait_mask;
270 /* Mask that excludes process input descriptor (s). */
272 static SELECT_TYPE non_process_wait_mask;
274 /* Mask of bits indicating the descriptors that we wait for connect to
275 complete on. Once they complete, they are removed from this mask
276 and added to the input_wait_mask and non_keyboard_wait_mask. */
278 static SELECT_TYPE connect_wait_mask;
280 /* Number of bits set in connect_wait_mask. */
281 static int num_pending_connects;
283 /* The largest descriptor currently in use for a process object. */
284 static int max_process_desc;
286 /* The largest descriptor currently in use for keyboard input. */
287 static int max_keyboard_desc;
289 /* Nonzero means delete a process right away if it exits. */
290 static int delete_exited_processes;
292 /* Indexed by descriptor, gives the process (if any) for that descriptor */
293 Lisp_Object chan_process[MAXDESC];
295 /* Alist of elements (NAME . PROCESS) */
296 Lisp_Object Vprocess_alist;
298 /* Buffered-ahead input char from process, indexed by channel.
299 -1 means empty (no char is buffered).
300 Used on sys V where the only way to tell if there is any
301 output from the process is to read at least one char.
302 Always -1 on systems that support FIONREAD. */
304 /* Don't make static; need to access externally. */
305 int proc_buffered_char[MAXDESC];
307 /* Table of `struct coding-system' for each process. */
308 static struct coding_system *proc_decode_coding_system[MAXDESC];
309 static struct coding_system *proc_encode_coding_system[MAXDESC];
311 #ifdef DATAGRAM_SOCKETS
312 /* Table of `partner address' for datagram sockets. */
313 struct sockaddr_and_len {
314 struct sockaddr *sa;
315 int len;
316 } datagram_address[MAXDESC];
317 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
318 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XINT (XPROCESS (proc)->infd)].sa != 0)
319 #else
320 #define DATAGRAM_CHAN_P(chan) (0)
321 #define DATAGRAM_CONN_P(proc) (0)
322 #endif
324 static Lisp_Object get_process ();
325 static void exec_sentinel ();
327 extern EMACS_TIME timer_check ();
328 extern int timers_run;
330 /* Maximum number of bytes to send to a pty without an eof. */
331 static int pty_max_bytes;
333 extern Lisp_Object Vfile_name_coding_system, Vdefault_file_name_coding_system;
335 #ifdef HAVE_PTYS
336 #ifdef HAVE_PTY_H
337 #include <pty.h>
338 #endif
339 /* The file name of the pty opened by allocate_pty. */
341 static char pty_name[24];
342 #endif
344 /* Compute the Lisp form of the process status, p->status, from
345 the numeric status that was returned by `wait'. */
347 Lisp_Object status_convert ();
349 void
350 update_status (p)
351 struct Lisp_Process *p;
353 union { int i; WAITTYPE wt; } u;
354 u.i = XFASTINT (p->raw_status_low) + (XFASTINT (p->raw_status_high) << 16);
355 p->status = status_convert (u.wt);
356 p->raw_status_low = Qnil;
357 p->raw_status_high = Qnil;
360 /* Convert a process status word in Unix format to
361 the list that we use internally. */
363 Lisp_Object
364 status_convert (w)
365 WAITTYPE w;
367 if (WIFSTOPPED (w))
368 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
369 else if (WIFEXITED (w))
370 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
371 WCOREDUMP (w) ? Qt : Qnil));
372 else if (WIFSIGNALED (w))
373 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
374 WCOREDUMP (w) ? Qt : Qnil));
375 else
376 return Qrun;
379 /* Given a status-list, extract the three pieces of information
380 and store them individually through the three pointers. */
382 void
383 decode_status (l, symbol, code, coredump)
384 Lisp_Object l;
385 Lisp_Object *symbol;
386 int *code;
387 int *coredump;
389 Lisp_Object tem;
391 if (SYMBOLP (l))
393 *symbol = l;
394 *code = 0;
395 *coredump = 0;
397 else
399 *symbol = XCAR (l);
400 tem = XCDR (l);
401 *code = XFASTINT (XCAR (tem));
402 tem = XCDR (tem);
403 *coredump = !NILP (tem);
407 /* Return a string describing a process status list. */
409 Lisp_Object
410 status_message (status)
411 Lisp_Object status;
413 Lisp_Object symbol;
414 int code, coredump;
415 Lisp_Object string, string2;
417 decode_status (status, &symbol, &code, &coredump);
419 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
421 char *signame;
422 synchronize_system_messages_locale ();
423 signame = strsignal (code);
424 if (signame == 0)
425 signame = "unknown";
426 string = build_string (signame);
427 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
428 SSET (string, 0, DOWNCASE (SREF (string, 0)));
429 return concat2 (string, string2);
431 else if (EQ (symbol, Qexit))
433 if (code == 0)
434 return build_string ("finished\n");
435 string = Fnumber_to_string (make_number (code));
436 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
437 return concat3 (build_string ("exited abnormally with code "),
438 string, string2);
440 else if (EQ (symbol, Qfailed))
442 string = Fnumber_to_string (make_number (code));
443 string2 = build_string ("\n");
444 return concat3 (build_string ("failed with code "),
445 string, string2);
447 else
448 return Fcopy_sequence (Fsymbol_name (symbol));
451 #ifdef HAVE_PTYS
453 /* Open an available pty, returning a file descriptor.
454 Return -1 on failure.
455 The file name of the terminal corresponding to the pty
456 is left in the variable pty_name. */
459 allocate_pty ()
461 struct stat stb;
462 register int c, i;
463 int fd;
465 /* Some systems name their pseudoterminals so that there are gaps in
466 the usual sequence - for example, on HP9000/S700 systems, there
467 are no pseudoterminals with names ending in 'f'. So we wait for
468 three failures in a row before deciding that we've reached the
469 end of the ptys. */
470 int failed_count = 0;
472 #ifdef PTY_ITERATION
473 PTY_ITERATION
474 #else
475 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
476 for (i = 0; i < 16; i++)
477 #endif
479 #ifdef PTY_NAME_SPRINTF
480 PTY_NAME_SPRINTF
481 #else
482 sprintf (pty_name, "/dev/pty%c%x", c, i);
483 #endif /* no PTY_NAME_SPRINTF */
485 #ifdef PTY_OPEN
486 PTY_OPEN;
487 #else /* no PTY_OPEN */
488 #ifdef IRIS
489 /* Unusual IRIS code */
490 *ptyv = emacs_open ("/dev/ptc", O_RDWR | O_NDELAY, 0);
491 if (fd < 0)
492 return -1;
493 if (fstat (fd, &stb) < 0)
494 return -1;
495 #else /* not IRIS */
496 if (stat (pty_name, &stb) < 0)
498 failed_count++;
499 if (failed_count >= 3)
500 return -1;
502 else
503 failed_count = 0;
504 #ifdef O_NONBLOCK
505 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
506 #else
507 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
508 #endif
509 #endif /* not IRIS */
510 #endif /* no PTY_OPEN */
512 if (fd >= 0)
514 /* check to make certain that both sides are available
515 this avoids a nasty yet stupid bug in rlogins */
516 #ifdef PTY_TTY_NAME_SPRINTF
517 PTY_TTY_NAME_SPRINTF
518 #else
519 sprintf (pty_name, "/dev/tty%c%x", c, i);
520 #endif /* no PTY_TTY_NAME_SPRINTF */
521 #ifndef UNIPLUS
522 if (access (pty_name, 6) != 0)
524 emacs_close (fd);
525 #if !defined(IRIS) && !defined(__sgi)
526 continue;
527 #else
528 return -1;
529 #endif /* IRIS */
531 #endif /* not UNIPLUS */
532 setup_pty (fd);
533 return fd;
536 return -1;
538 #endif /* HAVE_PTYS */
540 Lisp_Object
541 make_process (name)
542 Lisp_Object name;
544 register Lisp_Object val, tem, name1;
545 register struct Lisp_Process *p;
546 char suffix[10];
547 register int i;
549 p = allocate_process ();
551 XSETINT (p->infd, -1);
552 XSETINT (p->outfd, -1);
553 XSETFASTINT (p->pid, 0);
554 XSETFASTINT (p->tick, 0);
555 XSETFASTINT (p->update_tick, 0);
556 p->raw_status_low = Qnil;
557 p->raw_status_high = Qnil;
558 p->status = Qrun;
559 p->mark = Fmake_marker ();
561 /* If name is already in use, modify it until it is unused. */
563 name1 = name;
564 for (i = 1; ; i++)
566 tem = Fget_process (name1);
567 if (NILP (tem)) break;
568 sprintf (suffix, "<%d>", i);
569 name1 = concat2 (name, build_string (suffix));
571 name = name1;
572 p->name = name;
573 XSETPROCESS (val, p);
574 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
575 return val;
578 void
579 remove_process (proc)
580 register Lisp_Object proc;
582 register Lisp_Object pair;
584 pair = Frassq (proc, Vprocess_alist);
585 Vprocess_alist = Fdelq (pair, Vprocess_alist);
587 deactivate_process (proc);
590 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
591 doc: /* Return t if OBJECT is a process. */)
592 (object)
593 Lisp_Object object;
595 return PROCESSP (object) ? Qt : Qnil;
598 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
599 doc: /* Return the process named NAME, or nil if there is none. */)
600 (name)
601 register Lisp_Object name;
603 if (PROCESSP (name))
604 return name;
605 CHECK_STRING (name);
606 return Fcdr (Fassoc (name, Vprocess_alist));
609 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
610 doc: /* Return the (or a) process associated with BUFFER.
611 BUFFER may be a buffer or the name of one. */)
612 (buffer)
613 register Lisp_Object buffer;
615 register Lisp_Object buf, tail, proc;
617 if (NILP (buffer)) return Qnil;
618 buf = Fget_buffer (buffer);
619 if (NILP (buf)) return Qnil;
621 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
623 proc = Fcdr (Fcar (tail));
624 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
625 return proc;
627 return Qnil;
630 /* This is how commands for the user decode process arguments. It
631 accepts a process, a process name, a buffer, a buffer name, or nil.
632 Buffers denote the first process in the buffer, and nil denotes the
633 current buffer. */
635 static Lisp_Object
636 get_process (name)
637 register Lisp_Object name;
639 register Lisp_Object proc, obj;
640 if (STRINGP (name))
642 obj = Fget_process (name);
643 if (NILP (obj))
644 obj = Fget_buffer (name);
645 if (NILP (obj))
646 error ("Process %s does not exist", SDATA (name));
648 else if (NILP (name))
649 obj = Fcurrent_buffer ();
650 else
651 obj = name;
653 /* Now obj should be either a buffer object or a process object.
655 if (BUFFERP (obj))
657 proc = Fget_buffer_process (obj);
658 if (NILP (proc))
659 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
661 else
663 CHECK_PROCESS (obj);
664 proc = obj;
666 return proc;
669 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
670 doc: /* Delete PROCESS: kill it and forget about it immediately.
671 PROCESS may be a process, a buffer, the name of a process or buffer, or
672 nil, indicating the current buffer's process. */)
673 (process)
674 register Lisp_Object process;
676 process = get_process (process);
677 XPROCESS (process)->raw_status_low = Qnil;
678 XPROCESS (process)->raw_status_high = Qnil;
679 if (NETCONN_P (process))
681 XPROCESS (process)->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
682 XSETINT (XPROCESS (process)->tick, ++process_tick);
684 else if (XINT (XPROCESS (process)->infd) >= 0)
686 Fkill_process (process, Qnil);
687 /* Do this now, since remove_process will make sigchld_handler do nothing. */
688 XPROCESS (process)->status
689 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
690 XSETINT (XPROCESS (process)->tick, ++process_tick);
691 status_notify ();
693 remove_process (process);
694 return Qnil;
697 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
698 doc: /* Return the status of PROCESS.
699 The returned value is one of the following symbols:
700 run -- for a process that is running.
701 stop -- for a process stopped but continuable.
702 exit -- for a process that has exited.
703 signal -- for a process that has got a fatal signal.
704 open -- for a network stream connection that is open.
705 listen -- for a network stream server that is listening.
706 closed -- for a network stream connection that is closed.
707 connect -- when waiting for a non-blocking connection to complete.
708 failed -- when a non-blocking connection has failed.
709 nil -- if arg is a process name and no such process exists.
710 PROCESS may be a process, a buffer, the name of a process, or
711 nil, indicating the current buffer's process. */)
712 (process)
713 register Lisp_Object process;
715 register struct Lisp_Process *p;
716 register Lisp_Object status;
718 if (STRINGP (process))
719 process = Fget_process (process);
720 else
721 process = get_process (process);
723 if (NILP (process))
724 return process;
726 p = XPROCESS (process);
727 if (!NILP (p->raw_status_low))
728 update_status (p);
729 status = p->status;
730 if (CONSP (status))
731 status = XCAR (status);
732 if (NETCONN1_P (p))
734 if (EQ (status, Qexit))
735 status = Qclosed;
736 else if (EQ (p->command, Qt))
737 status = Qstop;
738 else if (EQ (status, Qrun))
739 status = Qopen;
741 return status;
744 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
745 1, 1, 0,
746 doc: /* Return the exit status of PROCESS or the signal number that killed it.
747 If PROCESS has not yet exited or died, return 0. */)
748 (process)
749 register Lisp_Object process;
751 CHECK_PROCESS (process);
752 if (!NILP (XPROCESS (process)->raw_status_low))
753 update_status (XPROCESS (process));
754 if (CONSP (XPROCESS (process)->status))
755 return XCAR (XCDR (XPROCESS (process)->status));
756 return make_number (0);
759 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
760 doc: /* Return the process id of PROCESS.
761 This is the pid of the Unix process which PROCESS uses or talks to.
762 For a network connection, this value is nil. */)
763 (process)
764 register Lisp_Object process;
766 CHECK_PROCESS (process);
767 return XPROCESS (process)->pid;
770 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
771 doc: /* Return the name of PROCESS, as a string.
772 This is the name of the program invoked in PROCESS,
773 possibly modified to make it unique among process names. */)
774 (process)
775 register Lisp_Object process;
777 CHECK_PROCESS (process);
778 return XPROCESS (process)->name;
781 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
782 doc: /* Return the command that was executed to start PROCESS.
783 This is a list of strings, the first string being the program executed
784 and the rest of the strings being the arguments given to it.
785 For a non-child channel, this is nil. */)
786 (process)
787 register Lisp_Object process;
789 CHECK_PROCESS (process);
790 return XPROCESS (process)->command;
793 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
794 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
795 This is the terminal that the process itself reads and writes on,
796 not the name of the pty that Emacs uses to talk with that terminal. */)
797 (process)
798 register Lisp_Object process;
800 CHECK_PROCESS (process);
801 return XPROCESS (process)->tty_name;
804 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
805 2, 2, 0,
806 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
807 (process, buffer)
808 register Lisp_Object process, buffer;
810 struct Lisp_Process *p;
812 CHECK_PROCESS (process);
813 if (!NILP (buffer))
814 CHECK_BUFFER (buffer);
815 p = XPROCESS (process);
816 p->buffer = buffer;
817 if (NETCONN1_P (p))
818 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
819 return buffer;
822 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
823 1, 1, 0,
824 doc: /* Return the buffer PROCESS is associated with.
825 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
826 (process)
827 register Lisp_Object process;
829 CHECK_PROCESS (process);
830 return XPROCESS (process)->buffer;
833 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
834 1, 1, 0,
835 doc: /* Return the marker for the end of the last output from PROCESS. */)
836 (process)
837 register Lisp_Object process;
839 CHECK_PROCESS (process);
840 return XPROCESS (process)->mark;
843 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
844 2, 2, 0,
845 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
846 t means stop accepting output from the process.
847 When a process has a filter, each time it does output
848 the entire string of output is passed to the filter.
849 The filter gets two arguments: the process and the string of output.
850 If the process has a filter, its buffer is not used for output. */)
851 (process, filter)
852 register Lisp_Object process, filter;
854 struct Lisp_Process *p;
856 CHECK_PROCESS (process);
857 p = XPROCESS (process);
859 /* Don't signal an error if the process' input file descriptor
860 is closed. This could make debugging Lisp more difficult,
861 for example when doing something like
863 (setq process (start-process ...))
864 (debug)
865 (set-process-filter process ...) */
867 if (XINT (p->infd) >= 0)
869 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
871 FD_CLR (XINT (p->infd), &input_wait_mask);
872 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
874 else if (EQ (p->filter, Qt)
875 && !EQ (p->command, Qt)) /* Network process not stopped. */
877 FD_SET (XINT (p->infd), &input_wait_mask);
878 FD_SET (XINT (p->infd), &non_keyboard_wait_mask);
882 p->filter = filter;
883 if (NETCONN1_P (p))
884 p->childp = Fplist_put (p->childp, QCfilter, filter);
885 return filter;
888 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
889 1, 1, 0,
890 doc: /* Returns the filter function of PROCESS; nil if none.
891 See `set-process-filter' for more info on filter functions. */)
892 (process)
893 register Lisp_Object process;
895 CHECK_PROCESS (process);
896 return XPROCESS (process)->filter;
899 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
900 2, 2, 0,
901 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
902 The sentinel is called as a function when the process changes state.
903 It gets two arguments: the process, and a string describing the change. */)
904 (process, sentinel)
905 register Lisp_Object process, sentinel;
907 CHECK_PROCESS (process);
908 XPROCESS (process)->sentinel = sentinel;
909 return sentinel;
912 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
913 1, 1, 0,
914 doc: /* Return the sentinel of PROCESS; nil if none.
915 See `set-process-sentinel' for more info on sentinels. */)
916 (process)
917 register Lisp_Object process;
919 CHECK_PROCESS (process);
920 return XPROCESS (process)->sentinel;
923 DEFUN ("set-process-window-size", Fset_process_window_size,
924 Sset_process_window_size, 3, 3, 0,
925 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
926 (process, height, width)
927 register Lisp_Object process, height, width;
929 CHECK_PROCESS (process);
930 CHECK_NATNUM (height);
931 CHECK_NATNUM (width);
933 if (XINT (XPROCESS (process)->infd) < 0
934 || set_window_size (XINT (XPROCESS (process)->infd),
935 XINT (height), XINT (width)) <= 0)
936 return Qnil;
937 else
938 return Qt;
941 DEFUN ("set-process-inherit-coding-system-flag",
942 Fset_process_inherit_coding_system_flag,
943 Sset_process_inherit_coding_system_flag, 2, 2, 0,
944 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
945 If the second argument FLAG is non-nil, then the variable
946 `buffer-file-coding-system' of the buffer associated with PROCESS
947 will be bound to the value of the coding system used to decode
948 the process output.
950 This is useful when the coding system specified for the process buffer
951 leaves either the character code conversion or the end-of-line conversion
952 unspecified, or if the coding system used to decode the process output
953 is more appropriate for saving the process buffer.
955 Binding the variable `inherit-process-coding-system' to non-nil before
956 starting the process is an alternative way of setting the inherit flag
957 for the process which will run. */)
958 (process, flag)
959 register Lisp_Object process, flag;
961 CHECK_PROCESS (process);
962 XPROCESS (process)->inherit_coding_system_flag = flag;
963 return flag;
966 DEFUN ("process-inherit-coding-system-flag",
967 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
968 1, 1, 0,
969 doc: /* Return the value of inherit-coding-system flag for PROCESS.
970 If this flag is t, `buffer-file-coding-system' of the buffer
971 associated with PROCESS will inherit the coding system used to decode
972 the process output. */)
973 (process)
974 register Lisp_Object process;
976 CHECK_PROCESS (process);
977 return XPROCESS (process)->inherit_coding_system_flag;
980 DEFUN ("set-process-query-on-exit-flag",
981 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
982 2, 2, 0,
983 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
984 If the second argument FLAG is non-nil, emacs will query the user before
985 exiting if PROCESS is running. */)
986 (process, flag)
987 register Lisp_Object process, flag;
989 CHECK_PROCESS (process);
990 XPROCESS (process)->kill_without_query = Fnull (flag);
991 return flag;
994 DEFUN ("process-query-on-exit-flag",
995 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
996 1, 1, 0,
997 doc: /* Return the current value of query on exit flag for PROCESS. */)
998 (process)
999 register Lisp_Object process;
1001 CHECK_PROCESS (process);
1002 return Fnull (XPROCESS (process)->kill_without_query);
1005 #ifdef DATAGRAM_SOCKETS
1006 Lisp_Object Fprocess_datagram_address ();
1007 #endif
1009 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1010 1, 2, 0,
1011 doc: /* Return the contact info of PROCESS; t for a real child.
1012 For a net connection, the value depends on the optional KEY arg.
1013 If KEY is nil, value is a cons cell of the form (HOST SERVICE),
1014 if KEY is t, the complete contact information for the connection is
1015 returned, else the specific value for the keyword KEY is returned.
1016 See `make-network-process' for a list of keywords. */)
1017 (process, key)
1018 register Lisp_Object process, key;
1020 Lisp_Object contact;
1022 CHECK_PROCESS (process);
1023 contact = XPROCESS (process)->childp;
1025 #ifdef DATAGRAM_SOCKETS
1026 if (DATAGRAM_CONN_P (process)
1027 && (EQ (key, Qt) || EQ (key, QCremote)))
1028 contact = Fplist_put (contact, QCremote,
1029 Fprocess_datagram_address (process));
1030 #endif
1032 if (!NETCONN_P (process) || EQ (key, Qt))
1033 return contact;
1034 if (NILP (key))
1035 return Fcons (Fplist_get (contact, QChost),
1036 Fcons (Fplist_get (contact, QCservice), Qnil));
1037 return Fplist_get (contact, key);
1040 #if 0 /* Turned off because we don't currently record this info
1041 in the process. Perhaps add it. */
1042 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1043 doc: /* Return the connection type of PROCESS.
1044 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1045 a socket connection. */)
1046 (process)
1047 Lisp_Object process;
1049 return XPROCESS (process)->type;
1051 #endif
1053 #ifdef HAVE_SOCKETS
1054 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1055 1, 1, 0,
1056 doc: /* Convert network ADDRESS from internal format to a string.
1057 Returns nil if format of ADDRESS is invalid. */)
1058 (address)
1059 Lisp_Object address;
1061 if (NILP (address))
1062 return Qnil;
1064 if (STRINGP (address)) /* AF_LOCAL */
1065 return address;
1067 if (VECTORP (address)) /* AF_INET */
1069 register struct Lisp_Vector *p = XVECTOR (address);
1070 Lisp_Object args[6];
1072 if (p->size != 5)
1073 return Qnil;
1075 args[0] = build_string ("%d.%d.%d.%d:%d");
1076 args[1] = p->contents[0];
1077 args[2] = p->contents[1];
1078 args[3] = p->contents[2];
1079 args[4] = p->contents[3];
1080 args[5] = p->contents[4];
1081 return Fformat (6, args);
1084 if (CONSP (address))
1086 Lisp_Object args[2];
1087 args[0] = build_string ("<Family %d>");
1088 args[1] = Fcar (address);
1089 return Fformat (2, args);
1093 return Qnil;
1095 #endif
1097 Lisp_Object
1098 list_processes_1 (query_only)
1099 Lisp_Object query_only;
1101 register Lisp_Object tail, tem;
1102 Lisp_Object proc, minspace, tem1;
1103 register struct Lisp_Process *p;
1104 char tembuf[300];
1105 int w_proc, w_buffer, w_tty;
1106 Lisp_Object i_status, i_buffer, i_tty, i_command;
1108 w_proc = 4; /* Proc */
1109 w_buffer = 6; /* Buffer */
1110 w_tty = 0; /* Omit if no ttys */
1112 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
1114 int i;
1116 proc = Fcdr (Fcar (tail));
1117 p = XPROCESS (proc);
1118 if (NILP (p->childp))
1119 continue;
1120 if (!NILP (query_only) && !NILP (p->kill_without_query))
1121 continue;
1122 if (STRINGP (p->name)
1123 && ( i = SCHARS (p->name), (i > w_proc)))
1124 w_proc = i;
1125 if (!NILP (p->buffer))
1127 if (NILP (XBUFFER (p->buffer)->name) && w_buffer < 8)
1128 w_buffer = 8; /* (Killed) */
1129 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1130 w_buffer = i;
1132 if (STRINGP (p->tty_name)
1133 && (i = SCHARS (p->tty_name), (i > w_tty)))
1134 w_tty = i;
1137 XSETFASTINT (i_status, w_proc + 1);
1138 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1139 if (w_tty)
1141 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1142 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_tty + 1);
1143 } else {
1144 i_tty = Qnil;
1145 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1148 XSETFASTINT (minspace, 1);
1150 set_buffer_internal (XBUFFER (Vstandard_output));
1151 Fbuffer_disable_undo (Vstandard_output);
1153 current_buffer->truncate_lines = Qt;
1155 write_string ("Proc", -1);
1156 Findent_to (i_status, minspace); write_string ("Status", -1);
1157 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1158 if (!NILP (i_tty))
1160 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1162 Findent_to (i_command, minspace); write_string ("Command", -1);
1163 write_string ("\n", -1);
1165 write_string ("----", -1);
1166 Findent_to (i_status, minspace); write_string ("------", -1);
1167 Findent_to (i_buffer, minspace); write_string ("------", -1);
1168 if (!NILP (i_tty))
1170 Findent_to (i_tty, minspace); write_string ("---", -1);
1172 Findent_to (i_command, minspace); write_string ("-------", -1);
1173 write_string ("\n", -1);
1175 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
1177 Lisp_Object symbol;
1179 proc = Fcdr (Fcar (tail));
1180 p = XPROCESS (proc);
1181 if (NILP (p->childp))
1182 continue;
1183 if (!NILP (query_only) && !NILP (p->kill_without_query))
1184 continue;
1186 Finsert (1, &p->name);
1187 Findent_to (i_status, minspace);
1189 if (!NILP (p->raw_status_low))
1190 update_status (p);
1191 symbol = p->status;
1192 if (CONSP (p->status))
1193 symbol = XCAR (p->status);
1196 if (EQ (symbol, Qsignal))
1198 Lisp_Object tem;
1199 tem = Fcar (Fcdr (p->status));
1200 #ifdef VMS
1201 if (XINT (tem) < NSIG)
1202 write_string (sys_errlist [XINT (tem)], -1);
1203 else
1204 #endif
1205 Fprinc (symbol, Qnil);
1207 else if (NETCONN1_P (p))
1209 if (EQ (symbol, Qexit))
1210 write_string ("closed", -1);
1211 else if (EQ (p->command, Qt))
1212 write_string ("stopped", -1);
1213 else if (EQ (symbol, Qrun))
1214 write_string ("open", -1);
1215 else
1216 Fprinc (symbol, Qnil);
1218 else
1219 Fprinc (symbol, Qnil);
1221 if (EQ (symbol, Qexit))
1223 Lisp_Object tem;
1224 tem = Fcar (Fcdr (p->status));
1225 if (XFASTINT (tem))
1227 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1228 write_string (tembuf, -1);
1232 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
1233 remove_process (proc);
1235 Findent_to (i_buffer, minspace);
1236 if (NILP (p->buffer))
1237 insert_string ("(none)");
1238 else if (NILP (XBUFFER (p->buffer)->name))
1239 insert_string ("(Killed)");
1240 else
1241 Finsert (1, &XBUFFER (p->buffer)->name);
1243 if (!NILP (i_tty))
1245 Findent_to (i_tty, minspace);
1246 if (STRINGP (p->tty_name))
1247 Finsert (1, &p->tty_name);
1250 Findent_to (i_command, minspace);
1252 if (EQ (p->status, Qlisten))
1254 Lisp_Object port = Fplist_get (p->childp, QCservice);
1255 if (INTEGERP (port))
1256 port = Fnumber_to_string (port);
1257 if (NILP (port))
1258 port = Fformat_network_address (Fplist_get (p->childp, QClocal));
1259 sprintf (tembuf, "(network %s server on %s)\n",
1260 (DATAGRAM_CHAN_P (XINT (p->infd)) ? "datagram" : "stream"),
1261 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1262 insert_string (tembuf);
1264 else if (NETCONN1_P (p))
1266 /* For a local socket, there is no host name,
1267 so display service instead. */
1268 Lisp_Object host = Fplist_get (p->childp, QChost);
1269 if (!STRINGP (host))
1271 host = Fplist_get (p->childp, QCservice);
1272 if (INTEGERP (host))
1273 host = Fnumber_to_string (host);
1275 if (NILP (host))
1276 host = Fformat_network_address (Fplist_get (p->childp, QCremote));
1277 sprintf (tembuf, "(network %s connection to %s)\n",
1278 (DATAGRAM_CHAN_P (XINT (p->infd)) ? "datagram" : "stream"),
1279 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1280 insert_string (tembuf);
1282 else
1284 tem = p->command;
1285 while (1)
1287 tem1 = Fcar (tem);
1288 Finsert (1, &tem1);
1289 tem = Fcdr (tem);
1290 if (NILP (tem))
1291 break;
1292 insert_string (" ");
1294 insert_string ("\n");
1297 return Qnil;
1300 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1301 doc: /* Display a list of all processes.
1302 If optional argument QUERY-ONLY is non-nil, only processes with
1303 the query-on-exit flag set will be listed.
1304 Any process listed as exited or signaled is actually eliminated
1305 after the listing is made. */)
1306 (query_only)
1307 Lisp_Object query_only;
1309 internal_with_output_to_temp_buffer ("*Process List*",
1310 list_processes_1, query_only);
1311 return Qnil;
1314 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1315 doc: /* Return a list of all processes. */)
1318 return Fmapcar (Qcdr, Vprocess_alist);
1321 /* Starting asynchronous inferior processes. */
1323 static Lisp_Object start_process_unwind ();
1325 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1326 doc: /* Start a program in a subprocess. Return the process object for it.
1327 NAME is name for process. It is modified if necessary to make it unique.
1328 BUFFER is the buffer or (buffer-name) to associate with the process.
1329 Process output goes at end of that buffer, unless you specify
1330 an output stream or filter function to handle the output.
1331 BUFFER may be also nil, meaning that this process is not associated
1332 with any buffer.
1333 Third arg is program file name. It is searched for in PATH.
1334 Remaining arguments are strings to give program as arguments.
1336 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1337 (nargs, args)
1338 int nargs;
1339 register Lisp_Object *args;
1341 Lisp_Object buffer, name, program, proc, current_dir, tem;
1342 #ifdef VMS
1343 register unsigned char *new_argv;
1344 int len;
1345 #else
1346 register unsigned char **new_argv;
1347 #endif
1348 register int i;
1349 int count = SPECPDL_INDEX ();
1351 buffer = args[1];
1352 if (!NILP (buffer))
1353 buffer = Fget_buffer_create (buffer);
1355 /* Make sure that the child will be able to chdir to the current
1356 buffer's current directory, or its unhandled equivalent. We
1357 can't just have the child check for an error when it does the
1358 chdir, since it's in a vfork.
1360 We have to GCPRO around this because Fexpand_file_name and
1361 Funhandled_file_name_directory might call a file name handling
1362 function. The argument list is protected by the caller, so all
1363 we really have to worry about is buffer. */
1365 struct gcpro gcpro1, gcpro2;
1367 current_dir = current_buffer->directory;
1369 GCPRO2 (buffer, current_dir);
1371 current_dir
1372 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
1373 Qnil);
1374 if (NILP (Ffile_accessible_directory_p (current_dir)))
1375 report_file_error ("Setting current directory",
1376 Fcons (current_buffer->directory, Qnil));
1378 UNGCPRO;
1381 name = args[0];
1382 CHECK_STRING (name);
1384 program = args[2];
1386 CHECK_STRING (program);
1388 proc = make_process (name);
1389 /* If an error occurs and we can't start the process, we want to
1390 remove it from the process list. This means that each error
1391 check in create_process doesn't need to call remove_process
1392 itself; it's all taken care of here. */
1393 record_unwind_protect (start_process_unwind, proc);
1395 XPROCESS (proc)->childp = Qt;
1396 XPROCESS (proc)->command_channel_p = Qnil;
1397 XPROCESS (proc)->buffer = buffer;
1398 XPROCESS (proc)->sentinel = Qnil;
1399 XPROCESS (proc)->filter = Qnil;
1400 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1402 /* Make the process marker point into the process buffer (if any). */
1403 if (!NILP (buffer))
1404 set_marker_both (XPROCESS (proc)->mark, buffer,
1405 BUF_ZV (XBUFFER (buffer)),
1406 BUF_ZV_BYTE (XBUFFER (buffer)));
1409 /* Decide coding systems for communicating with the process. Here
1410 we don't setup the structure coding_system nor pay attention to
1411 unibyte mode. They are done in create_process. */
1413 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1414 Lisp_Object coding_systems = Qt;
1415 Lisp_Object val, *args2;
1416 struct gcpro gcpro1, gcpro2;
1418 val = Vcoding_system_for_read;
1419 if (NILP (val))
1421 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1422 args2[0] = Qstart_process;
1423 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1424 GCPRO2 (proc, current_dir);
1425 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1426 UNGCPRO;
1427 if (CONSP (coding_systems))
1428 val = XCAR (coding_systems);
1429 else if (CONSP (Vdefault_process_coding_system))
1430 val = XCAR (Vdefault_process_coding_system);
1432 XPROCESS (proc)->decode_coding_system = val;
1434 val = Vcoding_system_for_write;
1435 if (NILP (val))
1437 if (EQ (coding_systems, Qt))
1439 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1440 args2[0] = Qstart_process;
1441 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1442 GCPRO2 (proc, current_dir);
1443 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1444 UNGCPRO;
1446 if (CONSP (coding_systems))
1447 val = XCDR (coding_systems);
1448 else if (CONSP (Vdefault_process_coding_system))
1449 val = XCDR (Vdefault_process_coding_system);
1451 XPROCESS (proc)->encode_coding_system = val;
1454 #ifdef VMS
1455 /* Make a one member argv with all args concatenated
1456 together separated by a blank. */
1457 len = SBYTES (program) + 2;
1458 for (i = 3; i < nargs; i++)
1460 tem = args[i];
1461 CHECK_STRING (tem);
1462 len += SBYTES (tem) + 1; /* count the blank */
1464 new_argv = (unsigned char *) alloca (len);
1465 strcpy (new_argv, SDATA (program));
1466 for (i = 3; i < nargs; i++)
1468 tem = args[i];
1469 CHECK_STRING (tem);
1470 strcat (new_argv, " ");
1471 strcat (new_argv, SDATA (tem));
1473 /* Need to add code here to check for program existence on VMS */
1475 #else /* not VMS */
1476 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1478 /* If program file name is not absolute, search our path for it.
1479 Put the name we will really use in TEM. */
1480 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1481 && !(SCHARS (program) > 1
1482 && IS_DEVICE_SEP (SREF (program, 1))))
1484 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1486 tem = Qnil;
1487 GCPRO4 (name, program, buffer, current_dir);
1488 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1489 UNGCPRO;
1490 if (NILP (tem))
1491 report_file_error ("Searching for program", Fcons (program, Qnil));
1492 tem = Fexpand_file_name (tem, Qnil);
1494 else
1496 if (!NILP (Ffile_directory_p (program)))
1497 error ("Specified program for new process is a directory");
1498 tem = program;
1501 /* If program file name starts with /: for quoting a magic name,
1502 discard that. */
1503 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1504 && SREF (tem, 1) == ':')
1505 tem = Fsubstring (tem, make_number (2), Qnil);
1507 /* Encode the file name and put it in NEW_ARGV.
1508 That's where the child will use it to execute the program. */
1509 tem = ENCODE_FILE (tem);
1510 new_argv[0] = SDATA (tem);
1512 /* Here we encode arguments by the coding system used for sending
1513 data to the process. We don't support using different coding
1514 systems for encoding arguments and for encoding data sent to the
1515 process. */
1517 for (i = 3; i < nargs; i++)
1519 tem = args[i];
1520 CHECK_STRING (tem);
1521 if (STRING_MULTIBYTE (tem))
1522 tem = (code_convert_string_norecord
1523 (tem, XPROCESS (proc)->encode_coding_system, 1));
1524 new_argv[i - 2] = SDATA (tem);
1526 new_argv[i - 2] = 0;
1527 #endif /* not VMS */
1529 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1530 XPROCESS (proc)->decoding_carryover = make_number (0);
1531 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1532 XPROCESS (proc)->encoding_carryover = make_number (0);
1534 XPROCESS (proc)->inherit_coding_system_flag
1535 = (NILP (buffer) || !inherit_process_coding_system
1536 ? Qnil : Qt);
1538 create_process (proc, (char **) new_argv, current_dir);
1540 return unbind_to (count, proc);
1543 /* This function is the unwind_protect form for Fstart_process. If
1544 PROC doesn't have its pid set, then we know someone has signaled
1545 an error and the process wasn't started successfully, so we should
1546 remove it from the process list. */
1547 static Lisp_Object
1548 start_process_unwind (proc)
1549 Lisp_Object proc;
1551 if (!PROCESSP (proc))
1552 abort ();
1554 /* Was PROC started successfully? */
1555 if (XINT (XPROCESS (proc)->pid) <= 0)
1556 remove_process (proc);
1558 return Qnil;
1561 void
1562 create_process_1 (timer)
1563 struct atimer *timer;
1565 /* Nothing to do. */
1569 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1570 #ifdef USG
1571 #ifdef SIGCHLD
1572 /* Mimic blocking of signals on system V, which doesn't really have it. */
1574 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1575 int sigchld_deferred;
1577 SIGTYPE
1578 create_process_sigchld ()
1580 signal (SIGCHLD, create_process_sigchld);
1582 sigchld_deferred = 1;
1584 #endif
1585 #endif
1586 #endif
1588 #ifndef VMS /* VMS version of this function is in vmsproc.c. */
1589 void
1590 create_process (process, new_argv, current_dir)
1591 Lisp_Object process;
1592 char **new_argv;
1593 Lisp_Object current_dir;
1595 int pid, inchannel, outchannel;
1596 int sv[2];
1597 #ifdef POSIX_SIGNALS
1598 sigset_t procmask;
1599 sigset_t blocked;
1600 struct sigaction sigint_action;
1601 struct sigaction sigquit_action;
1602 #ifdef AIX
1603 struct sigaction sighup_action;
1604 #endif
1605 #else /* !POSIX_SIGNALS */
1606 #if 0
1607 #ifdef SIGCHLD
1608 SIGTYPE (*sigchld)();
1609 #endif
1610 #endif /* 0 */
1611 #endif /* !POSIX_SIGNALS */
1612 /* Use volatile to protect variables from being clobbered by longjmp. */
1613 volatile int forkin, forkout;
1614 volatile int pty_flag = 0;
1615 #ifndef USE_CRT_DLL
1616 extern char **environ;
1617 #endif
1619 inchannel = outchannel = -1;
1621 #ifdef HAVE_PTYS
1622 if (!NILP (Vprocess_connection_type))
1623 outchannel = inchannel = allocate_pty ();
1625 if (inchannel >= 0)
1627 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1628 /* On most USG systems it does not work to open the pty's tty here,
1629 then close it and reopen it in the child. */
1630 #ifdef O_NOCTTY
1631 /* Don't let this terminal become our controlling terminal
1632 (in case we don't have one). */
1633 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1634 #else
1635 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1636 #endif
1637 if (forkin < 0)
1638 report_file_error ("Opening pty", Qnil);
1639 #else
1640 forkin = forkout = -1;
1641 #endif /* not USG, or USG_SUBTTY_WORKS */
1642 pty_flag = 1;
1644 else
1645 #endif /* HAVE_PTYS */
1646 #ifdef SKTPAIR
1648 if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
1649 report_file_error ("Opening socketpair", Qnil);
1650 outchannel = inchannel = sv[0];
1651 forkout = forkin = sv[1];
1653 #else /* not SKTPAIR */
1655 int tem;
1656 tem = pipe (sv);
1657 if (tem < 0)
1658 report_file_error ("Creating pipe", Qnil);
1659 inchannel = sv[0];
1660 forkout = sv[1];
1661 tem = pipe (sv);
1662 if (tem < 0)
1664 emacs_close (inchannel);
1665 emacs_close (forkout);
1666 report_file_error ("Creating pipe", Qnil);
1668 outchannel = sv[1];
1669 forkin = sv[0];
1671 #endif /* not SKTPAIR */
1673 #if 0
1674 /* Replaced by close_process_descs */
1675 set_exclusive_use (inchannel);
1676 set_exclusive_use (outchannel);
1677 #endif
1679 /* Stride people say it's a mystery why this is needed
1680 as well as the O_NDELAY, but that it fails without this. */
1681 #if defined (STRIDE) || (defined (pfa) && defined (HAVE_PTYS))
1683 int one = 1;
1684 ioctl (inchannel, FIONBIO, &one);
1686 #endif
1688 #ifdef O_NONBLOCK
1689 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1690 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1691 #else
1692 #ifdef O_NDELAY
1693 fcntl (inchannel, F_SETFL, O_NDELAY);
1694 fcntl (outchannel, F_SETFL, O_NDELAY);
1695 #endif
1696 #endif
1698 /* Record this as an active process, with its channels.
1699 As a result, child_setup will close Emacs's side of the pipes. */
1700 chan_process[inchannel] = process;
1701 XSETINT (XPROCESS (process)->infd, inchannel);
1702 XSETINT (XPROCESS (process)->outfd, outchannel);
1703 /* Record the tty descriptor used in the subprocess. */
1704 if (forkin < 0)
1705 XPROCESS (process)->subtty = Qnil;
1706 else
1707 XSETFASTINT (XPROCESS (process)->subtty, forkin);
1708 XPROCESS (process)->pty_flag = (pty_flag ? Qt : Qnil);
1709 XPROCESS (process)->status = Qrun;
1710 if (!proc_decode_coding_system[inchannel])
1711 proc_decode_coding_system[inchannel]
1712 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
1713 setup_coding_system (XPROCESS (process)->decode_coding_system,
1714 proc_decode_coding_system[inchannel]);
1715 if (!proc_encode_coding_system[outchannel])
1716 proc_encode_coding_system[outchannel]
1717 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
1718 setup_coding_system (XPROCESS (process)->encode_coding_system,
1719 proc_encode_coding_system[outchannel]);
1721 /* Delay interrupts until we have a chance to store
1722 the new fork's pid in its process structure */
1723 #ifdef POSIX_SIGNALS
1724 sigemptyset (&blocked);
1725 #ifdef SIGCHLD
1726 sigaddset (&blocked, SIGCHLD);
1727 #endif
1728 #ifdef HAVE_WORKING_VFORK
1729 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1730 this sets the parent's signal handlers as well as the child's.
1731 So delay all interrupts whose handlers the child might munge,
1732 and record the current handlers so they can be restored later. */
1733 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1734 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1735 #ifdef AIX
1736 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1737 #endif
1738 #endif /* HAVE_WORKING_VFORK */
1739 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1740 #else /* !POSIX_SIGNALS */
1741 #ifdef SIGCHLD
1742 #ifdef BSD4_1
1743 sighold (SIGCHLD);
1744 #else /* not BSD4_1 */
1745 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1746 sigsetmask (sigmask (SIGCHLD));
1747 #else /* ordinary USG */
1748 #if 0
1749 sigchld_deferred = 0;
1750 sigchld = signal (SIGCHLD, create_process_sigchld);
1751 #endif
1752 #endif /* ordinary USG */
1753 #endif /* not BSD4_1 */
1754 #endif /* SIGCHLD */
1755 #endif /* !POSIX_SIGNALS */
1757 FD_SET (inchannel, &input_wait_mask);
1758 FD_SET (inchannel, &non_keyboard_wait_mask);
1759 if (inchannel > max_process_desc)
1760 max_process_desc = inchannel;
1762 /* Until we store the proper pid, enable sigchld_handler
1763 to recognize an unknown pid as standing for this process.
1764 It is very important not to let this `marker' value stay
1765 in the table after this function has returned; if it does
1766 it might cause call-process to hang and subsequent asynchronous
1767 processes to get their return values scrambled. */
1768 XSETINT (XPROCESS (process)->pid, -1);
1770 BLOCK_INPUT;
1773 /* child_setup must clobber environ on systems with true vfork.
1774 Protect it from permanent change. */
1775 char **save_environ = environ;
1777 current_dir = ENCODE_FILE (current_dir);
1779 #ifndef WINDOWSNT
1780 pid = vfork ();
1781 if (pid == 0)
1782 #endif /* not WINDOWSNT */
1784 int xforkin = forkin;
1785 int xforkout = forkout;
1787 #if 0 /* This was probably a mistake--it duplicates code later on,
1788 but fails to handle all the cases. */
1789 /* Make sure SIGCHLD is not blocked in the child. */
1790 sigsetmask (SIGEMPTYMASK);
1791 #endif
1793 /* Make the pty be the controlling terminal of the process. */
1794 #ifdef HAVE_PTYS
1795 /* First, disconnect its current controlling terminal. */
1796 #ifdef HAVE_SETSID
1797 /* We tried doing setsid only if pty_flag, but it caused
1798 process_set_signal to fail on SGI when using a pipe. */
1799 setsid ();
1800 /* Make the pty's terminal the controlling terminal. */
1801 if (pty_flag)
1803 #ifdef TIOCSCTTY
1804 /* We ignore the return value
1805 because faith@cs.unc.edu says that is necessary on Linux. */
1806 ioctl (xforkin, TIOCSCTTY, 0);
1807 #endif
1809 #else /* not HAVE_SETSID */
1810 #ifdef USG
1811 /* It's very important to call setpgrp here and no time
1812 afterwards. Otherwise, we lose our controlling tty which
1813 is set when we open the pty. */
1814 setpgrp ();
1815 #endif /* USG */
1816 #endif /* not HAVE_SETSID */
1817 #if defined (HAVE_TERMIOS) && defined (LDISC1)
1818 if (pty_flag && xforkin >= 0)
1820 struct termios t;
1821 tcgetattr (xforkin, &t);
1822 t.c_lflag = LDISC1;
1823 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1824 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1826 #else
1827 #if defined (NTTYDISC) && defined (TIOCSETD)
1828 if (pty_flag && xforkin >= 0)
1830 /* Use new line discipline. */
1831 int ldisc = NTTYDISC;
1832 ioctl (xforkin, TIOCSETD, &ldisc);
1834 #endif
1835 #endif
1836 #ifdef TIOCNOTTY
1837 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1838 can do TIOCSPGRP only to the process's controlling tty. */
1839 if (pty_flag)
1841 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1842 I can't test it since I don't have 4.3. */
1843 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1844 ioctl (j, TIOCNOTTY, 0);
1845 emacs_close (j);
1846 #ifndef USG
1847 /* In order to get a controlling terminal on some versions
1848 of BSD, it is necessary to put the process in pgrp 0
1849 before it opens the terminal. */
1850 #ifdef HAVE_SETPGID
1851 setpgid (0, 0);
1852 #else
1853 setpgrp (0, 0);
1854 #endif
1855 #endif
1857 #endif /* TIOCNOTTY */
1859 #if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
1860 /*** There is a suggestion that this ought to be a
1861 conditional on TIOCSPGRP,
1862 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1863 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1864 that system does seem to need this code, even though
1865 both HAVE_SETSID and TIOCSCTTY are defined. */
1866 /* Now close the pty (if we had it open) and reopen it.
1867 This makes the pty the controlling terminal of the subprocess. */
1868 if (pty_flag)
1870 #ifdef SET_CHILD_PTY_PGRP
1871 int pgrp = getpid ();
1872 #endif
1874 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1875 would work? */
1876 if (xforkin >= 0)
1877 emacs_close (xforkin);
1878 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1880 if (xforkin < 0)
1882 emacs_write (1, "Couldn't open the pty terminal ", 31);
1883 emacs_write (1, pty_name, strlen (pty_name));
1884 emacs_write (1, "\n", 1);
1885 _exit (1);
1888 #ifdef SET_CHILD_PTY_PGRP
1889 ioctl (xforkin, TIOCSPGRP, &pgrp);
1890 ioctl (xforkout, TIOCSPGRP, &pgrp);
1891 #endif
1893 #endif /* not UNIPLUS and not RTU and not DONT_REOPEN_PTY */
1895 #ifdef SETUP_SLAVE_PTY
1896 if (pty_flag)
1898 SETUP_SLAVE_PTY;
1900 #endif /* SETUP_SLAVE_PTY */
1901 #ifdef AIX
1902 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1903 Now reenable it in the child, so it will die when we want it to. */
1904 if (pty_flag)
1905 signal (SIGHUP, SIG_DFL);
1906 #endif
1907 #endif /* HAVE_PTYS */
1909 signal (SIGINT, SIG_DFL);
1910 signal (SIGQUIT, SIG_DFL);
1912 /* Stop blocking signals in the child. */
1913 #ifdef POSIX_SIGNALS
1914 sigprocmask (SIG_SETMASK, &procmask, 0);
1915 #else /* !POSIX_SIGNALS */
1916 #ifdef SIGCHLD
1917 #ifdef BSD4_1
1918 sigrelse (SIGCHLD);
1919 #else /* not BSD4_1 */
1920 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1921 sigsetmask (SIGEMPTYMASK);
1922 #else /* ordinary USG */
1923 #if 0
1924 signal (SIGCHLD, sigchld);
1925 #endif
1926 #endif /* ordinary USG */
1927 #endif /* not BSD4_1 */
1928 #endif /* SIGCHLD */
1929 #endif /* !POSIX_SIGNALS */
1931 if (pty_flag)
1932 child_setup_tty (xforkout);
1933 #ifdef WINDOWSNT
1934 pid = child_setup (xforkin, xforkout, xforkout,
1935 new_argv, 1, current_dir);
1936 #else /* not WINDOWSNT */
1937 child_setup (xforkin, xforkout, xforkout,
1938 new_argv, 1, current_dir);
1939 #endif /* not WINDOWSNT */
1941 environ = save_environ;
1944 UNBLOCK_INPUT;
1946 /* This runs in the Emacs process. */
1947 if (pid < 0)
1949 if (forkin >= 0)
1950 emacs_close (forkin);
1951 if (forkin != forkout && forkout >= 0)
1952 emacs_close (forkout);
1954 else
1956 /* vfork succeeded. */
1957 XSETFASTINT (XPROCESS (process)->pid, pid);
1959 #ifdef WINDOWSNT
1960 register_child (pid, inchannel);
1961 #endif /* WINDOWSNT */
1963 /* If the subfork execv fails, and it exits,
1964 this close hangs. I don't know why.
1965 So have an interrupt jar it loose. */
1967 struct atimer *timer;
1968 EMACS_TIME offset;
1970 stop_polling ();
1971 EMACS_SET_SECS_USECS (offset, 1, 0);
1972 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
1974 XPROCESS (process)->subtty = Qnil;
1975 if (forkin >= 0)
1976 emacs_close (forkin);
1978 cancel_atimer (timer);
1979 start_polling ();
1982 if (forkin != forkout && forkout >= 0)
1983 emacs_close (forkout);
1985 #ifdef HAVE_PTYS
1986 if (pty_flag)
1987 XPROCESS (process)->tty_name = build_string (pty_name);
1988 else
1989 #endif
1990 XPROCESS (process)->tty_name = Qnil;
1993 /* Restore the signal state whether vfork succeeded or not.
1994 (We will signal an error, below, if it failed.) */
1995 #ifdef POSIX_SIGNALS
1996 #ifdef HAVE_WORKING_VFORK
1997 /* Restore the parent's signal handlers. */
1998 sigaction (SIGINT, &sigint_action, 0);
1999 sigaction (SIGQUIT, &sigquit_action, 0);
2000 #ifdef AIX
2001 sigaction (SIGHUP, &sighup_action, 0);
2002 #endif
2003 #endif /* HAVE_WORKING_VFORK */
2004 /* Stop blocking signals in the parent. */
2005 sigprocmask (SIG_SETMASK, &procmask, 0);
2006 #else /* !POSIX_SIGNALS */
2007 #ifdef SIGCHLD
2008 #ifdef BSD4_1
2009 sigrelse (SIGCHLD);
2010 #else /* not BSD4_1 */
2011 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
2012 sigsetmask (SIGEMPTYMASK);
2013 #else /* ordinary USG */
2014 #if 0
2015 signal (SIGCHLD, sigchld);
2016 /* Now really handle any of these signals
2017 that came in during this function. */
2018 if (sigchld_deferred)
2019 kill (getpid (), SIGCHLD);
2020 #endif
2021 #endif /* ordinary USG */
2022 #endif /* not BSD4_1 */
2023 #endif /* SIGCHLD */
2024 #endif /* !POSIX_SIGNALS */
2026 /* Now generate the error if vfork failed. */
2027 if (pid < 0)
2028 report_file_error ("Doing vfork", Qnil);
2030 #endif /* not VMS */
2033 #ifdef HAVE_SOCKETS
2035 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2036 The address family of sa is not included in the result. */
2038 static Lisp_Object
2039 conv_sockaddr_to_lisp (sa, len)
2040 struct sockaddr *sa;
2041 int len;
2043 Lisp_Object address;
2044 int i;
2045 unsigned char *cp;
2046 register struct Lisp_Vector *p;
2048 switch (sa->sa_family)
2050 case AF_INET:
2052 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2053 len = sizeof (sin->sin_addr) + 1;
2054 address = Fmake_vector (make_number (len), Qnil);
2055 p = XVECTOR (address);
2056 p->contents[--len] = make_number (ntohs (sin->sin_port));
2057 cp = (unsigned char *)&sin->sin_addr;
2058 break;
2060 #ifdef HAVE_LOCAL_SOCKETS
2061 case AF_LOCAL:
2063 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2064 for (i = 0; i < sizeof (sockun->sun_path); i++)
2065 if (sockun->sun_path[i] == 0)
2066 break;
2067 return make_unibyte_string (sockun->sun_path, i);
2069 #endif
2070 default:
2071 len -= sizeof (sa->sa_family);
2072 address = Fcons (make_number (sa->sa_family),
2073 Fmake_vector (make_number (len), Qnil));
2074 p = XVECTOR (XCDR (address));
2075 cp = (unsigned char *) sa + sizeof (sa->sa_family);
2076 break;
2079 i = 0;
2080 while (i < len)
2081 p->contents[i++] = make_number (*cp++);
2083 return address;
2087 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2089 static int
2090 get_lisp_to_sockaddr_size (address, familyp)
2091 Lisp_Object address;
2092 int *familyp;
2094 register struct Lisp_Vector *p;
2096 if (VECTORP (address))
2098 p = XVECTOR (address);
2099 if (p->size == 5)
2101 *familyp = AF_INET;
2102 return sizeof (struct sockaddr_in);
2105 #ifdef HAVE_LOCAL_SOCKETS
2106 else if (STRINGP (address))
2108 *familyp = AF_LOCAL;
2109 return sizeof (struct sockaddr_un);
2111 #endif
2112 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2114 struct sockaddr *sa;
2115 *familyp = XINT (XCAR (address));
2116 p = XVECTOR (XCDR (address));
2117 return p->size + sizeof (sa->sa_family);
2119 return 0;
2122 /* Convert an address object (vector or string) to an internal sockaddr.
2123 Format of address has already been validated by size_lisp_to_sockaddr. */
2125 static void
2126 conv_lisp_to_sockaddr (family, address, sa, len)
2127 int family;
2128 Lisp_Object address;
2129 struct sockaddr *sa;
2130 int len;
2132 register struct Lisp_Vector *p;
2133 register unsigned char *cp;
2134 register int i;
2136 bzero (sa, len);
2137 sa->sa_family = family;
2139 if (VECTORP (address))
2141 p = XVECTOR (address);
2142 if (family == AF_INET)
2144 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2145 len = sizeof (sin->sin_addr) + 1;
2146 i = XINT (p->contents[--len]);
2147 sin->sin_port = htons (i);
2148 cp = (unsigned char *)&sin->sin_addr;
2151 else if (STRINGP (address))
2153 #ifdef HAVE_LOCAL_SOCKETS
2154 if (family == AF_LOCAL)
2156 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2157 cp = SDATA (address);
2158 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2159 sockun->sun_path[i] = *cp++;
2161 #endif
2162 return;
2164 else
2166 p = XVECTOR (XCDR (address));
2167 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2170 for (i = 0; i < len; i++)
2171 if (INTEGERP (p->contents[i]))
2172 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2175 #ifdef DATAGRAM_SOCKETS
2176 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2177 1, 1, 0,
2178 doc: /* Get the current datagram address associated with PROCESS. */)
2179 (process)
2180 Lisp_Object process;
2182 int channel;
2184 CHECK_PROCESS (process);
2186 if (!DATAGRAM_CONN_P (process))
2187 return Qnil;
2189 channel = XINT (XPROCESS (process)->infd);
2190 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2191 datagram_address[channel].len);
2194 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2195 2, 2, 0,
2196 doc: /* Set the datagram address for PROCESS to ADDRESS.
2197 Returns nil upon error setting address, ADDRESS otherwise. */)
2198 (process, address)
2199 Lisp_Object process, address;
2201 int channel;
2202 int family, len;
2204 CHECK_PROCESS (process);
2206 if (!DATAGRAM_CONN_P (process))
2207 return Qnil;
2209 channel = XINT (XPROCESS (process)->infd);
2211 len = get_lisp_to_sockaddr_size (address, &family);
2212 if (datagram_address[channel].len != len)
2213 return Qnil;
2214 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2215 return address;
2217 #endif
2220 static struct socket_options {
2221 /* The name of this option. Should be lowercase version of option
2222 name without SO_ prefix. */
2223 char *name;
2224 /* Length of name. */
2225 int nlen;
2226 /* Option level SOL_... */
2227 int optlevel;
2228 /* Option number SO_... */
2229 int optnum;
2230 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_STR, SOPT_LINGER } opttype;
2231 } socket_options[] =
2233 #ifdef SO_BINDTODEVICE
2234 { "bindtodevice", 12, SOL_SOCKET, SO_BINDTODEVICE, SOPT_STR },
2235 #endif
2236 #ifdef SO_BROADCAST
2237 { "broadcast", 9, SOL_SOCKET, SO_BROADCAST, SOPT_BOOL },
2238 #endif
2239 #ifdef SO_DONTROUTE
2240 { "dontroute", 9, SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL },
2241 #endif
2242 #ifdef SO_KEEPALIVE
2243 { "keepalive", 9, SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL },
2244 #endif
2245 #ifdef SO_LINGER
2246 { "linger", 6, SOL_SOCKET, SO_LINGER, SOPT_LINGER },
2247 #endif
2248 #ifdef SO_OOBINLINE
2249 { "oobinline", 9, SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL },
2250 #endif
2251 #ifdef SO_PRIORITY
2252 { "priority", 8, SOL_SOCKET, SO_PRIORITY, SOPT_INT },
2253 #endif
2254 #ifdef SO_REUSEADDR
2255 { "reuseaddr", 9, SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL },
2256 #endif
2257 { 0, 0, 0, 0, SOPT_UNKNOWN }
2260 /* Process list of socket options OPTS on socket S.
2261 Only check if options are supported is S < 0.
2262 If NO_ERROR is non-zero, continue silently if an option
2263 cannot be set.
2265 Each element specifies one option. An element is either a string
2266 "OPTION=VALUE" or a cons (OPTION . VALUE) where OPTION is a string
2267 or a symbol. */
2269 static int
2270 set_socket_options (s, opts, no_error)
2271 int s;
2272 Lisp_Object opts;
2273 int no_error;
2275 if (!CONSP (opts))
2276 opts = Fcons (opts, Qnil);
2278 while (CONSP (opts))
2280 Lisp_Object opt;
2281 Lisp_Object val;
2282 char *name, *arg;
2283 struct socket_options *sopt;
2284 int ret = 0;
2286 opt = XCAR (opts);
2287 opts = XCDR (opts);
2289 name = 0;
2290 val = Qt;
2291 if (CONSP (opt))
2293 val = XCDR (opt);
2294 opt = XCAR (opt);
2296 if (STRINGP (opt))
2297 name = (char *) SDATA (opt);
2298 else if (SYMBOLP (opt))
2299 name = (char *) SDATA (SYMBOL_NAME (opt));
2300 else {
2301 error ("Mal-formed option list");
2302 return 0;
2305 if (strncmp (name, "no", 2) == 0)
2307 val = Qnil;
2308 name += 2;
2311 arg = 0;
2312 for (sopt = socket_options; sopt->name; sopt++)
2313 if (strncmp (name, sopt->name, sopt->nlen) == 0)
2315 if (name[sopt->nlen] == 0)
2316 break;
2317 if (name[sopt->nlen] == '=')
2319 arg = name + sopt->nlen + 1;
2320 break;
2324 switch (sopt->opttype)
2326 case SOPT_BOOL:
2328 int optval;
2329 if (s < 0)
2330 return 1;
2331 if (arg)
2332 optval = (*arg == '0' || *arg == 'n') ? 0 : 1;
2333 else if (INTEGERP (val))
2334 optval = XINT (val) == 0 ? 0 : 1;
2335 else
2336 optval = NILP (val) ? 0 : 1;
2337 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2338 &optval, sizeof (optval));
2339 break;
2342 case SOPT_INT:
2344 int optval;
2345 if (arg)
2346 optval = atoi(arg);
2347 else if (INTEGERP (val))
2348 optval = XINT (val);
2349 else
2350 error ("Bad option argument for %s", name);
2351 if (s < 0)
2352 return 1;
2353 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2354 &optval, sizeof (optval));
2355 break;
2358 case SOPT_STR:
2360 if (!arg)
2362 if (NILP (val))
2363 arg = "";
2364 else if (STRINGP (val))
2365 arg = (char *) SDATA (val);
2366 else if (XSYMBOL (val))
2367 arg = (char *) SDATA (SYMBOL_NAME (val));
2368 else
2369 error ("Invalid argument to %s option", name);
2371 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2372 arg, strlen (arg));
2375 #ifdef SO_LINGER
2376 case SOPT_LINGER:
2378 struct linger linger;
2380 linger.l_onoff = 1;
2381 linger.l_linger = 0;
2383 if (s < 0)
2384 return 1;
2386 if (arg)
2388 if (*arg == 'n' || *arg == 't' || *arg == 'y')
2389 linger.l_onoff = (*arg == 'n') ? 0 : 1;
2390 else
2391 linger.l_linger = atoi(arg);
2393 else if (INTEGERP (val))
2394 linger.l_linger = XINT (val);
2395 else
2396 linger.l_onoff = NILP (val) ? 0 : 1;
2397 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2398 &linger, sizeof (linger));
2399 break;
2401 #endif
2402 default:
2403 if (s < 0)
2404 return 0;
2405 if (no_error)
2406 continue;
2407 error ("Unsupported option: %s", name);
2409 if (ret < 0 && ! no_error)
2410 report_file_error ("Cannot set network option: %s", opt);
2412 return 1;
2415 DEFUN ("set-network-process-options",
2416 Fset_network_process_options, Sset_network_process_options,
2417 1, MANY, 0,
2418 doc: /* Set one or more options for network process PROCESS.
2419 Each option is either a string "OPT=VALUE" or a cons (OPT . VALUE).
2420 A boolean value is false if it either zero or nil, true otherwise.
2422 The following options are known. Consult the relevant system manual
2423 pages for more information.
2425 bindtodevice=NAME -- bind to interface NAME, or remove binding if nil.
2426 broadcast=BOOL -- Allow send and receive of datagram broadcasts.
2427 dontroute=BOOL -- Only send to directly connected hosts.
2428 keepalive=BOOL -- Send keep-alive messages on network stream.
2429 linger=BOOL or TIMEOUT -- Send queued messages before closing.
2430 oobinline=BOOL -- Place out-of-band data in receive data stream.
2431 priority=INT -- Set protocol defined priority for sent packets.
2432 reuseaddr=BOOL -- Allow reusing a recently used address.
2434 usage: (set-network-process-options PROCESS &rest OPTIONS) */)
2435 (nargs, args)
2436 int nargs;
2437 Lisp_Object *args;
2439 Lisp_Object process;
2440 Lisp_Object opts;
2442 process = args[0];
2443 CHECK_PROCESS (process);
2444 if (nargs > 1 && XINT (XPROCESS (process)->infd) >= 0)
2446 opts = Flist (nargs, args);
2447 set_socket_options (XINT (XPROCESS (process)->infd), opts, 0);
2449 return process;
2452 /* A version of request_sigio suitable for a record_unwind_protect. */
2454 Lisp_Object
2455 unwind_request_sigio (dummy)
2456 Lisp_Object dummy;
2458 if (interrupt_input)
2459 request_sigio ();
2460 return Qnil;
2463 /* Create a network stream/datagram client/server process. Treated
2464 exactly like a normal process when reading and writing. Primary
2465 differences are in status display and process deletion. A network
2466 connection has no PID; you cannot signal it. All you can do is
2467 stop/continue it and deactivate/close it via delete-process */
2469 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2470 0, MANY, 0,
2471 doc: /* Create and return a network server or client process.
2473 In Emacs, network connections are represented by process objects, so
2474 input and output work as for subprocesses and `delete-process' closes
2475 a network connection. However, a network process has no process id,
2476 it cannot be signalled, and the status codes are different from normal
2477 processes.
2479 Arguments are specified as keyword/argument pairs. The following
2480 arguments are defined:
2482 :name NAME -- NAME is name for process. It is modified if necessary
2483 to make it unique.
2485 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2486 with the process. Process output goes at end of that buffer, unless
2487 you specify an output stream or filter function to handle the output.
2488 BUFFER may be also nil, meaning that this process is not associated
2489 with any buffer.
2491 :host HOST -- HOST is name of the host to connect to, or its IP
2492 address. The symbol `local' specifies the local host. If specified
2493 for a server process, it must be a valid name or address for the local
2494 host, and only clients connecting to that address will be accepted.
2496 :service SERVICE -- SERVICE is name of the service desired, or an
2497 integer specifying a port number to connect to. If SERVICE is t,
2498 a random port number is selected for the server.
2500 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2501 stream type connection, `datagram' creates a datagram type connection.
2503 :family FAMILY -- FAMILY is the address (and protocol) family for the
2504 service specified by HOST and SERVICE. The default address family is
2505 Inet (or IPv4) for the host and port number specified by HOST and
2506 SERVICE. Other address families supported are:
2507 local -- for a local (i.e. UNIX) address specified by SERVICE.
2509 :local ADDRESS -- ADDRESS is the local address used for the connection.
2510 This parameter is ignored when opening a client process. When specified
2511 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2513 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2514 connection. This parameter is ignored when opening a stream server
2515 process. For a datagram server process, it specifies the initial
2516 setting of the remote datagram address. When specified for a client
2517 process, the FAMILY, HOST, and SERVICE args are ignored.
2519 The format of ADDRESS depends on the address family:
2520 - An IPv4 address is represented as an vector of integers [A B C D P]
2521 corresponding to numeric IP address A.B.C.D and port number P.
2522 - A local address is represented as a string with the address in the
2523 local address space.
2524 - An "unsupported family" address is represented by a cons (F . AV)
2525 where F is the family number and AV is a vector containing the socket
2526 address data with one element per address data byte. Do not rely on
2527 this format in portable code, as it may depend on implementation
2528 defined constants, data sizes, and data structure alignment.
2530 :coding CODING -- CODING is coding system for this process.
2532 :options OPTIONS -- Set the specified options for the network process.
2533 See `set-network-process-options' for details.
2535 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2536 return without waiting for the connection to complete; instead, the
2537 sentinel function will be called with second arg matching "open" (if
2538 successful) or "failed" when the connect completes. Default is to use
2539 a blocking connect (i.e. wait) for stream type connections.
2541 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2542 running when emacs is exited.
2544 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2545 In the stopped state, a server process does not accept new
2546 connections, and a client process does not handle incoming traffic.
2547 The stopped state is cleared by `continue-process' and set by
2548 `stop-process'.
2550 :filter FILTER -- Install FILTER as the process filter.
2552 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2554 :log LOG -- Install LOG as the server process log function. This
2555 function is called when the server accepts a network connection from a
2556 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2557 is the server process, CLIENT is the new process for the connection,
2558 and MESSAGE is a string.
2560 :server BOOL -- if BOOL is non-nil, create a server process for the
2561 specified FAMILY, SERVICE, and connection type (stream or datagram).
2562 Default is a client process.
2564 A server process will listen for and accept connections from
2565 clients. When a client connection is accepted, a new network process
2566 is created for the connection with the following parameters:
2567 - The client's process name is constructed by concatenating the server
2568 process' NAME and a client identification string.
2569 - If the FILTER argument is non-nil, the client process will not get a
2570 separate process buffer; otherwise, the client's process buffer is a newly
2571 created buffer named after the server process' BUFFER name or process
2572 NAME concatenated with the client identification string.
2573 - The connection type and the process filter and sentinel parameters are
2574 inherited from the server process' TYPE, FILTER and SENTINEL.
2575 - The client process' contact info is set according to the client's
2576 addressing information (typically an IP address and a port number).
2578 Notice that the FILTER and SENTINEL args are never used directly by
2579 the server process. Also, the BUFFER argument is not used directly by
2580 the server process, but via the optional :log function, accepted (and
2581 failed) connections may be logged in the server process' buffer.
2583 usage: (make-network-process &rest ARGS) */)
2584 (nargs, args)
2585 int nargs;
2586 Lisp_Object *args;
2588 Lisp_Object proc;
2589 Lisp_Object contact;
2590 struct Lisp_Process *p;
2591 #ifdef HAVE_GETADDRINFO
2592 struct addrinfo ai, *res, *lres;
2593 struct addrinfo hints;
2594 char *portstring, portbuf[128];
2595 #else /* HAVE_GETADDRINFO */
2596 struct _emacs_addrinfo
2598 int ai_family;
2599 int ai_socktype;
2600 int ai_protocol;
2601 int ai_addrlen;
2602 struct sockaddr *ai_addr;
2603 struct _emacs_addrinfo *ai_next;
2604 } ai, *res, *lres;
2605 #endif /* HAVE_GETADDRINFO */
2606 struct sockaddr_in address_in;
2607 #ifdef HAVE_LOCAL_SOCKETS
2608 struct sockaddr_un address_un;
2609 #endif
2610 int port;
2611 int ret = 0;
2612 int xerrno = 0;
2613 int s = -1, outch, inch;
2614 struct gcpro gcpro1;
2615 int retry = 0;
2616 int count = SPECPDL_INDEX ();
2617 int count1;
2618 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2619 Lisp_Object tem;
2620 Lisp_Object name, buffer, host, service, address;
2621 Lisp_Object filter, sentinel;
2622 int is_non_blocking_client = 0;
2623 int is_server = 0;
2624 int socktype;
2625 int family = -1;
2627 if (nargs == 0)
2628 return Qnil;
2630 /* Save arguments for process-contact and clone-process. */
2631 contact = Flist (nargs, args);
2632 GCPRO1 (contact);
2634 #ifdef WINDOWSNT
2635 /* Ensure socket support is loaded if available. */
2636 init_winsock (TRUE);
2637 #endif
2639 /* :type TYPE (nil: stream, datagram */
2640 tem = Fplist_get (contact, QCtype);
2641 if (NILP (tem))
2642 socktype = SOCK_STREAM;
2643 #ifdef DATAGRAM_SOCKETS
2644 else if (EQ (tem, Qdatagram))
2645 socktype = SOCK_DGRAM;
2646 #endif
2647 else
2648 error ("Unsupported connection type");
2650 /* :server BOOL */
2651 tem = Fplist_get (contact, QCserver);
2652 if (!NILP (tem))
2654 /* Don't support network sockets when non-blocking mode is
2655 not available, since a blocked Emacs is not useful. */
2656 #if defined(TERM) || (!defined(O_NONBLOCK) && !defined(O_NDELAY))
2657 error ("Network servers not supported");
2658 #else
2659 is_server = 1;
2660 #endif
2663 /* Make QCaddress an alias for :local (server) or :remote (client). */
2664 QCaddress = is_server ? QClocal : QCremote;
2666 /* :wait BOOL */
2667 if (!is_server && socktype == SOCK_STREAM
2668 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2670 #ifndef NON_BLOCKING_CONNECT
2671 error ("Non-blocking connect not supported");
2672 #else
2673 is_non_blocking_client = 1;
2674 #endif
2677 name = Fplist_get (contact, QCname);
2678 buffer = Fplist_get (contact, QCbuffer);
2679 filter = Fplist_get (contact, QCfilter);
2680 sentinel = Fplist_get (contact, QCsentinel);
2682 CHECK_STRING (name);
2684 #ifdef TERM
2685 /* Let's handle TERM before things get complicated ... */
2686 host = Fplist_get (contact, QChost);
2687 CHECK_STRING (host);
2689 service = Fplist_get (contact, QCservice);
2690 if (INTEGERP (service))
2691 port = htons ((unsigned short) XINT (service));
2692 else
2694 struct servent *svc_info;
2695 CHECK_STRING (service);
2696 svc_info = getservbyname (SDATA (service), "tcp");
2697 if (svc_info == 0)
2698 error ("Unknown service: %s", SDATA (service));
2699 port = svc_info->s_port;
2702 s = connect_server (0);
2703 if (s < 0)
2704 report_file_error ("error creating socket", Fcons (name, Qnil));
2705 send_command (s, C_PORT, 0, "%s:%d", SDATA (host), ntohs (port));
2706 send_command (s, C_DUMB, 1, 0);
2708 #else /* not TERM */
2710 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2711 ai.ai_socktype = socktype;
2712 ai.ai_protocol = 0;
2713 ai.ai_next = NULL;
2714 res = &ai;
2716 /* :local ADDRESS or :remote ADDRESS */
2717 address = Fplist_get (contact, QCaddress);
2718 if (!NILP (address))
2720 host = service = Qnil;
2722 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2723 error ("Malformed :address");
2724 ai.ai_family = family;
2725 ai.ai_addr = alloca (ai.ai_addrlen);
2726 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2727 goto open_socket;
2730 /* :family FAMILY -- nil (for Inet), local, or integer. */
2731 tem = Fplist_get (contact, QCfamily);
2732 if (INTEGERP (tem))
2733 family = XINT (tem);
2734 else
2736 if (NILP (tem))
2737 family = AF_INET;
2738 #ifdef HAVE_LOCAL_SOCKETS
2739 else if (EQ (tem, Qlocal))
2740 family = AF_LOCAL;
2741 #endif
2743 if (family < 0)
2744 error ("Unknown address family");
2745 ai.ai_family = family;
2747 /* :service SERVICE -- string, integer (port number), or t (random port). */
2748 service = Fplist_get (contact, QCservice);
2750 #ifdef HAVE_LOCAL_SOCKETS
2751 if (family == AF_LOCAL)
2753 /* Host is not used. */
2754 host = Qnil;
2755 CHECK_STRING (service);
2756 bzero (&address_un, sizeof address_un);
2757 address_un.sun_family = AF_LOCAL;
2758 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
2759 ai.ai_addr = (struct sockaddr *) &address_un;
2760 ai.ai_addrlen = sizeof address_un;
2761 goto open_socket;
2763 #endif
2765 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2766 host = Fplist_get (contact, QChost);
2767 if (!NILP (host))
2769 if (EQ (host, Qlocal))
2770 host = build_string ("localhost");
2771 CHECK_STRING (host);
2774 /* Slow down polling to every ten seconds.
2775 Some kernels have a bug which causes retrying connect to fail
2776 after a connect. Polling can interfere with gethostbyname too. */
2777 #ifdef POLL_FOR_INPUT
2778 if (socktype == SOCK_STREAM)
2780 record_unwind_protect (unwind_stop_other_atimers, Qnil);
2781 bind_polling_period (10);
2783 #endif
2785 #ifdef HAVE_GETADDRINFO
2786 /* If we have a host, use getaddrinfo to resolve both host and service.
2787 Otherwise, use getservbyname to lookup the service. */
2788 if (!NILP (host))
2791 /* SERVICE can either be a string or int.
2792 Convert to a C string for later use by getaddrinfo. */
2793 if (EQ (service, Qt))
2794 portstring = "0";
2795 else if (INTEGERP (service))
2797 sprintf (portbuf, "%ld", (long) XINT (service));
2798 portstring = portbuf;
2800 else
2802 CHECK_STRING (service);
2803 portstring = SDATA (service);
2806 immediate_quit = 1;
2807 QUIT;
2808 memset (&hints, 0, sizeof (hints));
2809 hints.ai_flags = 0;
2810 hints.ai_family = NILP (Fplist_member (contact, QCfamily)) ? AF_UNSPEC : family;
2811 hints.ai_socktype = socktype;
2812 hints.ai_protocol = 0;
2813 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
2814 if (ret)
2815 #ifdef HAVE_GAI_STRERROR
2816 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
2817 #else
2818 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
2819 #endif
2820 immediate_quit = 0;
2822 goto open_socket;
2824 #endif /* HAVE_GETADDRINFO */
2826 /* We end up here if getaddrinfo is not defined, or in case no hostname
2827 has been specified (e.g. for a local server process). */
2829 if (EQ (service, Qt))
2830 port = 0;
2831 else if (INTEGERP (service))
2832 port = htons ((unsigned short) XINT (service));
2833 else
2835 struct servent *svc_info;
2836 CHECK_STRING (service);
2837 svc_info = getservbyname (SDATA (service),
2838 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
2839 if (svc_info == 0)
2840 error ("Unknown service: %s", SDATA (service));
2841 port = svc_info->s_port;
2844 bzero (&address_in, sizeof address_in);
2845 address_in.sin_family = family;
2846 address_in.sin_addr.s_addr = INADDR_ANY;
2847 address_in.sin_port = port;
2849 #ifndef HAVE_GETADDRINFO
2850 if (!NILP (host))
2852 struct hostent *host_info_ptr;
2854 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
2855 as it may `hang' emacs for a very long time. */
2856 immediate_quit = 1;
2857 QUIT;
2858 host_info_ptr = gethostbyname (SDATA (host));
2859 immediate_quit = 0;
2861 if (host_info_ptr)
2863 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
2864 host_info_ptr->h_length);
2865 family = host_info_ptr->h_addrtype;
2866 address_in.sin_family = family;
2868 else
2869 /* Attempt to interpret host as numeric inet address */
2871 IN_ADDR numeric_addr;
2872 numeric_addr = inet_addr ((char *) SDATA (host));
2873 if (NUMERIC_ADDR_ERROR)
2874 error ("Unknown host \"%s\"", SDATA (host));
2876 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
2877 sizeof (address_in.sin_addr));
2881 #endif /* not HAVE_GETADDRINFO */
2883 ai.ai_family = family;
2884 ai.ai_addr = (struct sockaddr *) &address_in;
2885 ai.ai_addrlen = sizeof address_in;
2887 open_socket:
2889 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
2890 when connect is interrupted. So let's not let it get interrupted.
2891 Note we do not turn off polling, because polling is only used
2892 when not interrupt_input, and thus not normally used on the systems
2893 which have this bug. On systems which use polling, there's no way
2894 to quit if polling is turned off. */
2895 if (interrupt_input
2896 && !is_server && socktype == SOCK_STREAM)
2898 /* Comment from KFS: The original open-network-stream code
2899 didn't unwind protect this, but it seems like the proper
2900 thing to do. In any case, I don't see how it could harm to
2901 do this -- and it makes cleanup (using unbind_to) easier. */
2902 record_unwind_protect (unwind_request_sigio, Qnil);
2903 unrequest_sigio ();
2906 /* Do this in case we never enter the for-loop below. */
2907 count1 = SPECPDL_INDEX ();
2908 s = -1;
2910 for (lres = res; lres; lres = lres->ai_next)
2912 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
2913 if (s < 0)
2915 xerrno = errno;
2916 continue;
2919 #ifdef DATAGRAM_SOCKETS
2920 if (!is_server && socktype == SOCK_DGRAM)
2921 break;
2922 #endif /* DATAGRAM_SOCKETS */
2924 #ifdef NON_BLOCKING_CONNECT
2925 if (is_non_blocking_client)
2927 #ifdef O_NONBLOCK
2928 ret = fcntl (s, F_SETFL, O_NONBLOCK);
2929 #else
2930 ret = fcntl (s, F_SETFL, O_NDELAY);
2931 #endif
2932 if (ret < 0)
2934 xerrno = errno;
2935 emacs_close (s);
2936 s = -1;
2937 continue;
2940 #endif
2942 /* Make us close S if quit. */
2943 record_unwind_protect (close_file_unwind, make_number (s));
2945 if (is_server)
2947 /* Configure as a server socket. */
2948 #ifdef HAVE_LOCAL_SOCKETS
2949 if (family != AF_LOCAL)
2950 #endif
2952 int optval = 1;
2953 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
2954 report_file_error ("Cannot set reuse option on server socket.", Qnil);
2957 if (bind (s, lres->ai_addr, lres->ai_addrlen))
2958 report_file_error ("Cannot bind server socket", Qnil);
2960 #ifdef HAVE_GETSOCKNAME
2961 if (EQ (service, Qt))
2963 struct sockaddr_in sa1;
2964 int len1 = sizeof (sa1);
2965 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
2967 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
2968 service = make_number (sa1.sin_port);
2969 contact = Fplist_put (contact, QCservice, service);
2972 #endif
2974 if (socktype == SOCK_STREAM && listen (s, 5))
2975 report_file_error ("Cannot listen on server socket", Qnil);
2977 break;
2980 retry_connect:
2982 immediate_quit = 1;
2983 QUIT;
2985 /* This turns off all alarm-based interrupts; the
2986 bind_polling_period call above doesn't always turn all the
2987 short-interval ones off, especially if interrupt_input is
2988 set.
2990 It'd be nice to be able to control the connect timeout
2991 though. Would non-blocking connect calls be portable?
2993 This used to be conditioned by HAVE_GETADDRINFO. Why? */
2995 turn_on_atimers (0);
2997 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
2998 xerrno = errno;
3000 turn_on_atimers (1);
3002 if (ret == 0 || xerrno == EISCONN)
3004 /* The unwind-protect will be discarded afterwards.
3005 Likewise for immediate_quit. */
3006 break;
3009 #ifdef NON_BLOCKING_CONNECT
3010 #ifdef EINPROGRESS
3011 if (is_non_blocking_client && xerrno == EINPROGRESS)
3012 break;
3013 #else
3014 #ifdef EWOULDBLOCK
3015 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3016 break;
3017 #endif
3018 #endif
3019 #endif
3021 immediate_quit = 0;
3023 if (xerrno == EINTR)
3024 goto retry_connect;
3025 if (xerrno == EADDRINUSE && retry < 20)
3027 /* A delay here is needed on some FreeBSD systems,
3028 and it is harmless, since this retrying takes time anyway
3029 and should be infrequent. */
3030 Fsleep_for (make_number (1), Qnil);
3031 retry++;
3032 goto retry_connect;
3035 /* Discard the unwind protect closing S. */
3036 specpdl_ptr = specpdl + count1;
3037 emacs_close (s);
3038 s = -1;
3041 if (s >= 0)
3043 #ifdef DATAGRAM_SOCKETS
3044 if (socktype == SOCK_DGRAM)
3046 if (datagram_address[s].sa)
3047 abort ();
3048 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3049 datagram_address[s].len = lres->ai_addrlen;
3050 if (is_server)
3052 Lisp_Object remote;
3053 bzero (datagram_address[s].sa, lres->ai_addrlen);
3054 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3056 int rfamily, rlen;
3057 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3058 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3059 conv_lisp_to_sockaddr (rfamily, remote,
3060 datagram_address[s].sa, rlen);
3063 else
3064 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3066 #endif
3067 contact = Fplist_put (contact, QCaddress,
3068 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3071 #ifdef HAVE_GETADDRINFO
3072 if (res != &ai)
3073 freeaddrinfo (res);
3074 #endif
3076 immediate_quit = 0;
3078 /* Discard the unwind protect for closing S, if any. */
3079 specpdl_ptr = specpdl + count1;
3081 /* Unwind bind_polling_period and request_sigio. */
3082 unbind_to (count, Qnil);
3084 if (s < 0)
3086 /* If non-blocking got this far - and failed - assume non-blocking is
3087 not supported after all. This is probably a wrong assumption, but
3088 the normal blocking calls to open-network-stream handles this error
3089 better. */
3090 if (is_non_blocking_client)
3091 return Qnil;
3093 errno = xerrno;
3094 if (is_server)
3095 report_file_error ("make server process failed", contact);
3096 else
3097 report_file_error ("make client process failed", contact);
3100 tem = Fplist_get (contact, QCoptions);
3101 if (!NILP (tem))
3102 set_socket_options (s, tem, 1);
3104 #endif /* not TERM */
3106 inch = s;
3107 outch = s;
3109 if (!NILP (buffer))
3110 buffer = Fget_buffer_create (buffer);
3111 proc = make_process (name);
3113 chan_process[inch] = proc;
3115 #ifdef O_NONBLOCK
3116 fcntl (inch, F_SETFL, O_NONBLOCK);
3117 #else
3118 #ifdef O_NDELAY
3119 fcntl (inch, F_SETFL, O_NDELAY);
3120 #endif
3121 #endif
3123 p = XPROCESS (proc);
3125 p->childp = contact;
3126 p->buffer = buffer;
3127 p->sentinel = sentinel;
3128 p->filter = filter;
3129 p->log = Fplist_get (contact, QClog);
3130 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3131 p->kill_without_query = Qt;
3132 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3133 p->command = Qt;
3134 p->pid = Qnil;
3135 XSETINT (p->infd, inch);
3136 XSETINT (p->outfd, outch);
3137 if (is_server && socktype == SOCK_STREAM)
3138 p->status = Qlisten;
3140 #ifdef NON_BLOCKING_CONNECT
3141 if (is_non_blocking_client)
3143 /* We may get here if connect did succeed immediately. However,
3144 in that case, we still need to signal this like a non-blocking
3145 connection. */
3146 p->status = Qconnect;
3147 if (!FD_ISSET (inch, &connect_wait_mask))
3149 FD_SET (inch, &connect_wait_mask);
3150 num_pending_connects++;
3153 else
3154 #endif
3155 /* A server may have a client filter setting of Qt, but it must
3156 still listen for incoming connects unless it is stopped. */
3157 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3158 || (EQ (p->status, Qlisten) && NILP (p->command)))
3160 FD_SET (inch, &input_wait_mask);
3161 FD_SET (inch, &non_keyboard_wait_mask);
3164 if (inch > max_process_desc)
3165 max_process_desc = inch;
3167 tem = Fplist_member (contact, QCcoding);
3168 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3169 tem = Qnil; /* No error message (too late!). */
3172 /* Setup coding systems for communicating with the network stream. */
3173 struct gcpro gcpro1;
3174 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3175 Lisp_Object coding_systems = Qt;
3176 Lisp_Object args[5], val;
3178 if (!NILP (tem))
3179 val = XCAR (XCDR (tem));
3180 else if (!NILP (Vcoding_system_for_read))
3181 val = Vcoding_system_for_read;
3182 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3183 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3184 /* We dare not decode end-of-line format by setting VAL to
3185 Qraw_text, because the existing Emacs Lisp libraries
3186 assume that they receive bare code including a sequene of
3187 CR LF. */
3188 val = Qnil;
3189 else
3191 if (NILP (host) || NILP (service))
3192 coding_systems = Qnil;
3193 else
3195 args[0] = Qopen_network_stream, args[1] = name,
3196 args[2] = buffer, args[3] = host, args[4] = service;
3197 GCPRO1 (proc);
3198 coding_systems = Ffind_operation_coding_system (5, args);
3199 UNGCPRO;
3201 if (CONSP (coding_systems))
3202 val = XCAR (coding_systems);
3203 else if (CONSP (Vdefault_process_coding_system))
3204 val = XCAR (Vdefault_process_coding_system);
3205 else
3206 val = Qnil;
3208 p->decode_coding_system = val;
3210 if (!NILP (tem))
3211 val = XCAR (XCDR (tem));
3212 else if (!NILP (Vcoding_system_for_write))
3213 val = Vcoding_system_for_write;
3214 else if (NILP (current_buffer->enable_multibyte_characters))
3215 val = Qnil;
3216 else
3218 if (EQ (coding_systems, Qt))
3220 if (NILP (host) || NILP (service))
3221 coding_systems = Qnil;
3222 else
3224 args[0] = Qopen_network_stream, args[1] = name,
3225 args[2] = buffer, args[3] = host, args[4] = service;
3226 GCPRO1 (proc);
3227 coding_systems = Ffind_operation_coding_system (5, args);
3228 UNGCPRO;
3231 if (CONSP (coding_systems))
3232 val = XCDR (coding_systems);
3233 else if (CONSP (Vdefault_process_coding_system))
3234 val = XCDR (Vdefault_process_coding_system);
3235 else
3236 val = Qnil;
3238 p->encode_coding_system = val;
3241 if (!proc_decode_coding_system[inch])
3242 proc_decode_coding_system[inch]
3243 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
3244 setup_coding_system (p->decode_coding_system,
3245 proc_decode_coding_system[inch]);
3246 if (!proc_encode_coding_system[outch])
3247 proc_encode_coding_system[outch]
3248 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
3249 setup_coding_system (p->encode_coding_system,
3250 proc_encode_coding_system[outch]);
3252 p->decoding_buf = make_uninit_string (0);
3253 p->decoding_carryover = make_number (0);
3254 p->encoding_buf = make_uninit_string (0);
3255 p->encoding_carryover = make_number (0);
3257 p->inherit_coding_system_flag
3258 = (!NILP (tem) || NILP (buffer) || !inherit_process_coding_system
3259 ? Qnil : Qt);
3261 UNGCPRO;
3262 return proc;
3264 #endif /* HAVE_SOCKETS */
3266 void
3267 deactivate_process (proc)
3268 Lisp_Object proc;
3270 register int inchannel, outchannel;
3271 register struct Lisp_Process *p = XPROCESS (proc);
3273 inchannel = XINT (p->infd);
3274 outchannel = XINT (p->outfd);
3276 if (inchannel >= 0)
3278 /* Beware SIGCHLD hereabouts. */
3279 flush_pending_output (inchannel);
3280 #ifdef VMS
3282 VMS_PROC_STUFF *get_vms_process_pointer (), *vs;
3283 sys$dassgn (outchannel);
3284 vs = get_vms_process_pointer (p->pid);
3285 if (vs)
3286 give_back_vms_process_stuff (vs);
3288 #else
3289 emacs_close (inchannel);
3290 if (outchannel >= 0 && outchannel != inchannel)
3291 emacs_close (outchannel);
3292 #endif
3294 XSETINT (p->infd, -1);
3295 XSETINT (p->outfd, -1);
3296 #ifdef DATAGRAM_SOCKETS
3297 if (DATAGRAM_CHAN_P (inchannel))
3299 xfree (datagram_address[inchannel].sa);
3300 datagram_address[inchannel].sa = 0;
3301 datagram_address[inchannel].len = 0;
3303 #endif
3304 chan_process[inchannel] = Qnil;
3305 FD_CLR (inchannel, &input_wait_mask);
3306 FD_CLR (inchannel, &non_keyboard_wait_mask);
3307 if (FD_ISSET (inchannel, &connect_wait_mask))
3309 FD_CLR (inchannel, &connect_wait_mask);
3310 if (--num_pending_connects < 0)
3311 abort ();
3313 if (inchannel == max_process_desc)
3315 int i;
3316 /* We just closed the highest-numbered process input descriptor,
3317 so recompute the highest-numbered one now. */
3318 max_process_desc = 0;
3319 for (i = 0; i < MAXDESC; i++)
3320 if (!NILP (chan_process[i]))
3321 max_process_desc = i;
3326 /* Close all descriptors currently in use for communication
3327 with subprocess. This is used in a newly-forked subprocess
3328 to get rid of irrelevant descriptors. */
3330 void
3331 close_process_descs ()
3333 #ifndef WINDOWSNT
3334 int i;
3335 for (i = 0; i < MAXDESC; i++)
3337 Lisp_Object process;
3338 process = chan_process[i];
3339 if (!NILP (process))
3341 int in = XINT (XPROCESS (process)->infd);
3342 int out = XINT (XPROCESS (process)->outfd);
3343 if (in >= 0)
3344 emacs_close (in);
3345 if (out >= 0 && in != out)
3346 emacs_close (out);
3349 #endif
3352 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3353 0, 3, 0,
3354 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3355 It is read into the process' buffers or given to their filter functions.
3356 Non-nil arg PROCESS means do not return until some output has been received
3357 from PROCESS.
3358 Non-nil second arg TIMEOUT and third arg TIMEOUT-MSECS are number of
3359 seconds and microseconds to wait; return after that much time whether
3360 or not there is input.
3361 Return non-nil iff we received any output before the timeout expired. */)
3362 (process, timeout, timeout_msecs)
3363 register Lisp_Object process, timeout, timeout_msecs;
3365 int seconds;
3366 int useconds;
3368 if (! NILP (process))
3369 CHECK_PROCESS (process);
3371 if (! NILP (timeout_msecs))
3373 CHECK_NUMBER (timeout_msecs);
3374 useconds = XINT (timeout_msecs);
3375 if (!INTEGERP (timeout))
3376 XSETINT (timeout, 0);
3379 int carry = useconds / 1000000;
3381 XSETINT (timeout, XINT (timeout) + carry);
3382 useconds -= carry * 1000000;
3384 /* I think this clause is necessary because C doesn't
3385 guarantee a particular rounding direction for negative
3386 integers. */
3387 if (useconds < 0)
3389 XSETINT (timeout, XINT (timeout) - 1);
3390 useconds += 1000000;
3394 else
3395 useconds = 0;
3397 if (! NILP (timeout))
3399 CHECK_NUMBER (timeout);
3400 seconds = XINT (timeout);
3401 if (seconds < 0 || (seconds == 0 && useconds == 0))
3402 seconds = -1;
3404 else
3406 if (NILP (process))
3407 seconds = -1;
3408 else
3409 seconds = 0;
3412 if (NILP (process))
3413 XSETFASTINT (process, 0);
3415 return
3416 (wait_reading_process_input (seconds, useconds, process, 0)
3417 ? Qt : Qnil);
3420 /* Accept a connection for server process SERVER on CHANNEL. */
3422 static int connect_counter = 0;
3424 static void
3425 server_accept_connection (server, channel)
3426 Lisp_Object server;
3427 int channel;
3429 Lisp_Object proc, caller, name, buffer;
3430 Lisp_Object contact, host, service;
3431 struct Lisp_Process *ps= XPROCESS (server);
3432 struct Lisp_Process *p;
3433 int s;
3434 union u_sockaddr {
3435 struct sockaddr sa;
3436 struct sockaddr_in in;
3437 #ifdef HAVE_LOCAL_SOCKETS
3438 struct sockaddr_un un;
3439 #endif
3440 } saddr;
3441 int len = sizeof saddr;
3443 s = accept (channel, &saddr.sa, &len);
3445 if (s < 0)
3447 int code = errno;
3449 if (code == EAGAIN)
3450 return;
3451 #ifdef EWOULDBLOCK
3452 if (code == EWOULDBLOCK)
3453 return;
3454 #endif
3456 if (!NILP (ps->log))
3457 call3 (ps->log, server, Qnil,
3458 concat3 (build_string ("accept failed with code"),
3459 Fnumber_to_string (make_number (code)),
3460 build_string ("\n")));
3461 return;
3464 connect_counter++;
3466 /* Setup a new process to handle the connection. */
3468 /* Generate a unique identification of the caller, and build contact
3469 information for this process. */
3470 host = Qt;
3471 service = Qnil;
3472 switch (saddr.sa.sa_family)
3474 case AF_INET:
3476 Lisp_Object args[5];
3477 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
3478 args[0] = build_string ("%d.%d.%d.%d");
3479 args[1] = make_number (*ip++);
3480 args[2] = make_number (*ip++);
3481 args[3] = make_number (*ip++);
3482 args[4] = make_number (*ip++);
3483 host = Fformat (5, args);
3484 service = make_number (ntohs (saddr.in.sin_port));
3486 args[0] = build_string (" <%s:%d>");
3487 args[1] = host;
3488 args[2] = service;
3489 caller = Fformat (3, args);
3491 break;
3493 #ifdef HAVE_LOCAL_SOCKETS
3494 case AF_LOCAL:
3495 #endif
3496 default:
3497 caller = Fnumber_to_string (make_number (connect_counter));
3498 caller = concat3 (build_string (" <*"), caller, build_string ("*>"));
3499 break;
3502 /* Create a new buffer name for this process if it doesn't have a
3503 filter. The new buffer name is based on the buffer name or
3504 process name of the server process concatenated with the caller
3505 identification. */
3507 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
3508 buffer = Qnil;
3509 else
3511 buffer = ps->buffer;
3512 if (!NILP (buffer))
3513 buffer = Fbuffer_name (buffer);
3514 else
3515 buffer = ps->name;
3516 if (!NILP (buffer))
3518 buffer = concat2 (buffer, caller);
3519 buffer = Fget_buffer_create (buffer);
3523 /* Generate a unique name for the new server process. Combine the
3524 server process name with the caller identification. */
3526 name = concat2 (ps->name, caller);
3527 proc = make_process (name);
3529 chan_process[s] = proc;
3531 #ifdef O_NONBLOCK
3532 fcntl (s, F_SETFL, O_NONBLOCK);
3533 #else
3534 #ifdef O_NDELAY
3535 fcntl (s, F_SETFL, O_NDELAY);
3536 #endif
3537 #endif
3539 p = XPROCESS (proc);
3541 /* Build new contact information for this setup. */
3542 contact = Fcopy_sequence (ps->childp);
3543 contact = Fplist_put (contact, QCserver, Qnil);
3544 contact = Fplist_put (contact, QChost, host);
3545 if (!NILP (service))
3546 contact = Fplist_put (contact, QCservice, service);
3547 contact = Fplist_put (contact, QCremote,
3548 conv_sockaddr_to_lisp (&saddr.sa, len));
3549 #ifdef HAVE_GETSOCKNAME
3550 len = sizeof saddr;
3551 if (getsockname (channel, &saddr.sa, &len) == 0)
3552 contact = Fplist_put (contact, QClocal,
3553 conv_sockaddr_to_lisp (&saddr.sa, len));
3554 #endif
3556 p->childp = contact;
3557 p->buffer = buffer;
3558 p->sentinel = ps->sentinel;
3559 p->filter = ps->filter;
3560 p->command = Qnil;
3561 p->pid = Qnil;
3562 XSETINT (p->infd, s);
3563 XSETINT (p->outfd, s);
3564 p->status = Qrun;
3566 /* Client processes for accepted connections are not stopped initially. */
3567 if (!EQ (p->filter, Qt))
3569 FD_SET (s, &input_wait_mask);
3570 FD_SET (s, &non_keyboard_wait_mask);
3573 if (s > max_process_desc)
3574 max_process_desc = s;
3576 /* Setup coding system for new process based on server process.
3577 This seems to be the proper thing to do, as the coding system
3578 of the new process should reflect the settings at the time the
3579 server socket was opened; not the current settings. */
3581 p->decode_coding_system = ps->decode_coding_system;
3582 p->encode_coding_system = ps->encode_coding_system;
3584 if (!proc_decode_coding_system[s])
3585 proc_decode_coding_system[s]
3586 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
3587 setup_coding_system (p->decode_coding_system,
3588 proc_decode_coding_system[s]);
3589 if (!proc_encode_coding_system[s])
3590 proc_encode_coding_system[s]
3591 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
3592 setup_coding_system (p->encode_coding_system,
3593 proc_encode_coding_system[s]);
3595 p->decoding_buf = make_uninit_string (0);
3596 p->decoding_carryover = make_number (0);
3597 p->encoding_buf = make_uninit_string (0);
3598 p->encoding_carryover = make_number (0);
3600 p->inherit_coding_system_flag
3601 = (NILP (buffer) ? Qnil : ps->inherit_coding_system_flag);
3603 if (!NILP (ps->log))
3604 call3 (ps->log, server, proc,
3605 concat3 (build_string ("accept from "),
3606 (STRINGP (host) ? host : build_string ("-")),
3607 build_string ("\n")));
3609 if (!NILP (p->sentinel))
3610 exec_sentinel (proc,
3611 concat3 (build_string ("open from "),
3612 (STRINGP (host) ? host : build_string ("-")),
3613 build_string ("\n")));
3616 /* This variable is different from waiting_for_input in keyboard.c.
3617 It is used to communicate to a lisp process-filter/sentinel (via the
3618 function Fwaiting_for_user_input_p below) whether emacs was waiting
3619 for user-input when that process-filter was called.
3620 waiting_for_input cannot be used as that is by definition 0 when
3621 lisp code is being evalled.
3622 This is also used in record_asynch_buffer_change.
3623 For that purpose, this must be 0
3624 when not inside wait_reading_process_input. */
3625 static int waiting_for_user_input_p;
3627 /* This is here so breakpoints can be put on it. */
3628 static void
3629 wait_reading_process_input_1 ()
3633 /* Read and dispose of subprocess output while waiting for timeout to
3634 elapse and/or keyboard input to be available.
3636 TIME_LIMIT is:
3637 timeout in seconds, or
3638 zero for no limit, or
3639 -1 means gobble data immediately available but don't wait for any.
3641 MICROSECS is:
3642 an additional duration to wait, measured in microseconds.
3643 If this is nonzero and time_limit is 0, then the timeout
3644 consists of MICROSECS only.
3646 READ_KBD is a lisp value:
3647 0 to ignore keyboard input, or
3648 1 to return when input is available, or
3649 -1 meaning caller will actually read the input, so don't throw to
3650 the quit handler, or
3651 a cons cell, meaning wait until its car is non-nil
3652 (and gobble terminal input into the buffer if any arrives), or
3653 a process object, meaning wait until something arrives from that
3654 process. The return value is true iff we read some input from
3655 that process.
3657 DO_DISPLAY != 0 means redisplay should be done to show subprocess
3658 output that arrives.
3660 If READ_KBD is a pointer to a struct Lisp_Process, then the
3661 function returns true iff we received input from that process
3662 before the timeout elapsed.
3663 Otherwise, return true iff we received input from any process. */
3666 wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
3667 int time_limit, microsecs;
3668 Lisp_Object read_kbd;
3669 int do_display;
3671 register int channel, nfds;
3672 static SELECT_TYPE Available;
3673 static SELECT_TYPE Connecting;
3674 int check_connect, no_avail;
3675 int xerrno;
3676 Lisp_Object proc;
3677 EMACS_TIME timeout, end_time;
3678 int wait_channel = -1;
3679 struct Lisp_Process *wait_proc = 0;
3680 int got_some_input = 0;
3681 /* Either nil or a cons cell, the car of which is of interest and
3682 may be changed outside of this routine. */
3683 Lisp_Object wait_for_cell = Qnil;
3685 FD_ZERO (&Available);
3686 FD_ZERO (&Connecting);
3688 /* If read_kbd is a process to watch, set wait_proc and wait_channel
3689 accordingly. */
3690 if (PROCESSP (read_kbd))
3692 wait_proc = XPROCESS (read_kbd);
3693 wait_channel = XINT (wait_proc->infd);
3694 XSETFASTINT (read_kbd, 0);
3697 /* If waiting for non-nil in a cell, record where. */
3698 if (CONSP (read_kbd))
3700 wait_for_cell = read_kbd;
3701 XSETFASTINT (read_kbd, 0);
3704 waiting_for_user_input_p = XINT (read_kbd);
3706 /* Since we may need to wait several times,
3707 compute the absolute time to return at. */
3708 if (time_limit || microsecs)
3710 EMACS_GET_TIME (end_time);
3711 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
3712 EMACS_ADD_TIME (end_time, end_time, timeout);
3714 #ifdef POLLING_PROBLEM_IN_SELECT
3715 /* AlainF 5-Jul-1996
3716 HP-UX 10.10 seem to have problems with signals coming in
3717 Causes "poll: interrupted system call" messages when Emacs is run
3718 in an X window
3719 Turn off periodic alarms (in case they are in use),
3720 and then turn off any other atimers. */
3721 stop_polling ();
3722 turn_on_atimers (0);
3723 #endif
3725 while (1)
3727 int timeout_reduced_for_timers = 0;
3729 /* If calling from keyboard input, do not quit
3730 since we want to return C-g as an input character.
3731 Otherwise, do pending quit if requested. */
3732 if (XINT (read_kbd) >= 0)
3733 QUIT;
3735 /* Exit now if the cell we're waiting for became non-nil. */
3736 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
3737 break;
3739 /* Compute time from now till when time limit is up */
3740 /* Exit if already run out */
3741 if (time_limit == -1)
3743 /* -1 specified for timeout means
3744 gobble output available now
3745 but don't wait at all. */
3747 EMACS_SET_SECS_USECS (timeout, 0, 0);
3749 else if (time_limit || microsecs)
3751 EMACS_GET_TIME (timeout);
3752 EMACS_SUB_TIME (timeout, end_time, timeout);
3753 if (EMACS_TIME_NEG_P (timeout))
3754 break;
3756 else
3758 EMACS_SET_SECS_USECS (timeout, 100000, 0);
3761 /* Normally we run timers here.
3762 But not if wait_for_cell; in those cases,
3763 the wait is supposed to be short,
3764 and those callers cannot handle running arbitrary Lisp code here. */
3765 if (NILP (wait_for_cell))
3767 EMACS_TIME timer_delay;
3771 int old_timers_run = timers_run;
3772 struct buffer *old_buffer = current_buffer;
3774 timer_delay = timer_check (1);
3776 /* If a timer has run, this might have changed buffers
3777 an alike. Make read_key_sequence aware of that. */
3778 if (timers_run != old_timers_run
3779 && old_buffer != current_buffer
3780 && waiting_for_user_input_p == -1)
3781 record_asynch_buffer_change ();
3783 if (timers_run != old_timers_run && do_display)
3784 /* We must retry, since a timer may have requeued itself
3785 and that could alter the time_delay. */
3786 redisplay_preserve_echo_area (9);
3787 else
3788 break;
3790 while (!detect_input_pending ());
3792 /* If there is unread keyboard input, also return. */
3793 if (XINT (read_kbd) != 0
3794 && requeued_events_pending_p ())
3795 break;
3797 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
3799 EMACS_TIME difference;
3800 EMACS_SUB_TIME (difference, timer_delay, timeout);
3801 if (EMACS_TIME_NEG_P (difference))
3803 timeout = timer_delay;
3804 timeout_reduced_for_timers = 1;
3807 /* If time_limit is -1, we are not going to wait at all. */
3808 else if (time_limit != -1)
3810 /* This is so a breakpoint can be put here. */
3811 wait_reading_process_input_1 ();
3815 /* Cause C-g and alarm signals to take immediate action,
3816 and cause input available signals to zero out timeout.
3818 It is important that we do this before checking for process
3819 activity. If we get a SIGCHLD after the explicit checks for
3820 process activity, timeout is the only way we will know. */
3821 if (XINT (read_kbd) < 0)
3822 set_waiting_for_input (&timeout);
3824 /* If status of something has changed, and no input is
3825 available, notify the user of the change right away. After
3826 this explicit check, we'll let the SIGCHLD handler zap
3827 timeout to get our attention. */
3828 if (update_tick != process_tick && do_display)
3830 SELECT_TYPE Atemp, Ctemp;
3832 Atemp = input_wait_mask;
3833 #ifdef MAC_OSX
3834 /* On Mac OS X, the SELECT system call always says input is
3835 present (for reading) at stdin, even when none is. This
3836 causes the call to SELECT below to return 1 and
3837 status_notify not to be called. As a result output of
3838 subprocesses are incorrectly discarded. */
3839 FD_CLR (0, &Atemp);
3840 #endif
3841 Ctemp = connect_wait_mask;
3842 EMACS_SET_SECS_USECS (timeout, 0, 0);
3843 if ((select (max (max_process_desc, max_keyboard_desc) + 1,
3844 &Atemp,
3845 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
3846 (SELECT_TYPE *)0, &timeout)
3847 <= 0))
3849 /* It's okay for us to do this and then continue with
3850 the loop, since timeout has already been zeroed out. */
3851 clear_waiting_for_input ();
3852 status_notify ();
3856 /* Don't wait for output from a non-running process. Just
3857 read whatever data has already been received. */
3858 if (wait_proc != 0 && !NILP (wait_proc->raw_status_low))
3859 update_status (wait_proc);
3860 if (wait_proc != 0
3861 && ! EQ (wait_proc->status, Qrun)
3862 && ! EQ (wait_proc->status, Qconnect))
3864 int nread, total_nread = 0;
3866 clear_waiting_for_input ();
3867 XSETPROCESS (proc, wait_proc);
3869 /* Read data from the process, until we exhaust it. */
3870 while (XINT (wait_proc->infd) >= 0)
3872 nread = read_process_output (proc, XINT (wait_proc->infd));
3874 if (nread == 0)
3875 break;
3877 if (0 < nread)
3878 total_nread += nread;
3879 #ifdef EIO
3880 else if (nread == -1 && EIO == errno)
3881 break;
3882 #endif
3883 #ifdef EAGAIN
3884 else if (nread == -1 && EAGAIN == errno)
3885 break;
3886 #endif
3887 #ifdef EWOULDBLOCK
3888 else if (nread == -1 && EWOULDBLOCK == errno)
3889 break;
3890 #endif
3892 if (total_nread > 0 && do_display)
3893 redisplay_preserve_echo_area (10);
3895 break;
3898 /* Wait till there is something to do */
3900 if (!NILP (wait_for_cell))
3902 Available = non_process_wait_mask;
3903 check_connect = 0;
3905 else
3907 if (! XINT (read_kbd))
3908 Available = non_keyboard_wait_mask;
3909 else
3910 Available = input_wait_mask;
3911 check_connect = (num_pending_connects > 0);
3914 /* If frame size has changed or the window is newly mapped,
3915 redisplay now, before we start to wait. There is a race
3916 condition here; if a SIGIO arrives between now and the select
3917 and indicates that a frame is trashed, the select may block
3918 displaying a trashed screen. */
3919 if (frame_garbaged && do_display)
3921 clear_waiting_for_input ();
3922 redisplay_preserve_echo_area (11);
3923 if (XINT (read_kbd) < 0)
3924 set_waiting_for_input (&timeout);
3927 no_avail = 0;
3928 if (XINT (read_kbd) && detect_input_pending ())
3930 nfds = 0;
3931 no_avail = 1;
3933 else
3935 if (check_connect)
3936 Connecting = connect_wait_mask;
3937 nfds = select (max (max_process_desc, max_keyboard_desc) + 1,
3938 &Available,
3939 (check_connect ? &Connecting : (SELECT_TYPE *)0),
3940 (SELECT_TYPE *)0, &timeout);
3943 xerrno = errno;
3945 /* Make C-g and alarm signals set flags again */
3946 clear_waiting_for_input ();
3948 /* If we woke up due to SIGWINCH, actually change size now. */
3949 do_pending_window_change (0);
3951 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
3952 /* We wanted the full specified time, so return now. */
3953 break;
3954 if (nfds < 0)
3956 if (xerrno == EINTR)
3957 no_avail = 1;
3958 #ifdef ultrix
3959 /* Ultrix select seems to return ENOMEM when it is
3960 interrupted. Treat it just like EINTR. Bleah. Note
3961 that we want to test for the "ultrix" CPP symbol, not
3962 "__ultrix__"; the latter is only defined under GCC, but
3963 not by DEC's bundled CC. -JimB */
3964 else if (xerrno == ENOMEM)
3965 no_avail = 1;
3966 #endif
3967 #ifdef ALLIANT
3968 /* This happens for no known reason on ALLIANT.
3969 I am guessing that this is the right response. -- RMS. */
3970 else if (xerrno == EFAULT)
3971 no_avail = 1;
3972 #endif
3973 else if (xerrno == EBADF)
3975 #ifdef AIX
3976 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
3977 the child's closure of the pts gives the parent a SIGHUP, and
3978 the ptc file descriptor is automatically closed,
3979 yielding EBADF here or at select() call above.
3980 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
3981 in m/ibmrt-aix.h), and here we just ignore the select error.
3982 Cleanup occurs c/o status_notify after SIGCLD. */
3983 no_avail = 1; /* Cannot depend on values returned */
3984 #else
3985 abort ();
3986 #endif
3988 else
3989 error ("select error: %s", emacs_strerror (xerrno));
3992 if (no_avail)
3994 FD_ZERO (&Available);
3995 check_connect = 0;
3998 #if defined(sun) && !defined(USG5_4)
3999 if (nfds > 0 && keyboard_bit_set (&Available)
4000 && interrupt_input)
4001 /* System sometimes fails to deliver SIGIO.
4003 David J. Mackenzie says that Emacs doesn't compile under
4004 Solaris if this code is enabled, thus the USG5_4 in the CPP
4005 conditional. "I haven't noticed any ill effects so far.
4006 If you find a Solaris expert somewhere, they might know
4007 better." */
4008 kill (getpid (), SIGIO);
4009 #endif
4011 #if 0 /* When polling is used, interrupt_input is 0,
4012 so get_input_pending should read the input.
4013 So this should not be needed. */
4014 /* If we are using polling for input,
4015 and we see input available, make it get read now.
4016 Otherwise it might not actually get read for a second.
4017 And on hpux, since we turn off polling in wait_reading_process_input,
4018 it might never get read at all if we don't spend much time
4019 outside of wait_reading_process_input. */
4020 if (XINT (read_kbd) && interrupt_input
4021 && keyboard_bit_set (&Available)
4022 && input_polling_used ())
4023 kill (getpid (), SIGALRM);
4024 #endif
4026 /* Check for keyboard input */
4027 /* If there is any, return immediately
4028 to give it higher priority than subprocesses */
4030 if (XINT (read_kbd) != 0)
4032 int old_timers_run = timers_run;
4033 struct buffer *old_buffer = current_buffer;
4034 int leave = 0;
4036 if (detect_input_pending_run_timers (do_display))
4038 swallow_events (do_display);
4039 if (detect_input_pending_run_timers (do_display))
4040 leave = 1;
4043 /* If a timer has run, this might have changed buffers
4044 an alike. Make read_key_sequence aware of that. */
4045 if (timers_run != old_timers_run
4046 && waiting_for_user_input_p == -1
4047 && old_buffer != current_buffer)
4048 record_asynch_buffer_change ();
4050 if (leave)
4051 break;
4054 /* If there is unread keyboard input, also return. */
4055 if (XINT (read_kbd) != 0
4056 && requeued_events_pending_p ())
4057 break;
4059 /* If we are not checking for keyboard input now,
4060 do process events (but don't run any timers).
4061 This is so that X events will be processed.
4062 Otherwise they may have to wait until polling takes place.
4063 That would causes delays in pasting selections, for example.
4065 (We used to do this only if wait_for_cell.) */
4066 if (XINT (read_kbd) == 0 && detect_input_pending ())
4068 swallow_events (do_display);
4069 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4070 if (detect_input_pending ())
4071 break;
4072 #endif
4075 /* Exit now if the cell we're waiting for became non-nil. */
4076 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4077 break;
4079 #ifdef SIGIO
4080 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4081 go read it. This can happen with X on BSD after logging out.
4082 In that case, there really is no input and no SIGIO,
4083 but select says there is input. */
4085 if (XINT (read_kbd) && interrupt_input
4086 && keyboard_bit_set (&Available))
4087 kill (getpid (), SIGIO);
4088 #endif
4090 if (! wait_proc)
4091 got_some_input |= nfds > 0;
4093 /* If checking input just got us a size-change event from X,
4094 obey it now if we should. */
4095 if (XINT (read_kbd) || ! NILP (wait_for_cell))
4096 do_pending_window_change (0);
4098 /* Check for data from a process. */
4099 if (no_avail || nfds == 0)
4100 continue;
4102 /* Really FIRST_PROC_DESC should be 0 on Unix,
4103 but this is safer in the short run. */
4104 for (channel = 0; channel <= max_process_desc; channel++)
4106 if (FD_ISSET (channel, &Available)
4107 && FD_ISSET (channel, &non_keyboard_wait_mask))
4109 int nread;
4111 /* If waiting for this channel, arrange to return as
4112 soon as no more input to be processed. No more
4113 waiting. */
4114 if (wait_channel == channel)
4116 wait_channel = -1;
4117 time_limit = -1;
4118 got_some_input = 1;
4120 proc = chan_process[channel];
4121 if (NILP (proc))
4122 continue;
4124 /* If this is a server stream socket, accept connection. */
4125 if (EQ (XPROCESS (proc)->status, Qlisten))
4127 server_accept_connection (proc, channel);
4128 continue;
4131 /* Read data from the process, starting with our
4132 buffered-ahead character if we have one. */
4134 nread = read_process_output (proc, channel);
4135 if (nread > 0)
4137 /* Since read_process_output can run a filter,
4138 which can call accept-process-output,
4139 don't try to read from any other processes
4140 before doing the select again. */
4141 FD_ZERO (&Available);
4143 if (do_display)
4144 redisplay_preserve_echo_area (12);
4146 #ifdef EWOULDBLOCK
4147 else if (nread == -1 && errno == EWOULDBLOCK)
4149 #endif
4150 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4151 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4152 #ifdef O_NONBLOCK
4153 else if (nread == -1 && errno == EAGAIN)
4155 #else
4156 #ifdef O_NDELAY
4157 else if (nread == -1 && errno == EAGAIN)
4159 /* Note that we cannot distinguish between no input
4160 available now and a closed pipe.
4161 With luck, a closed pipe will be accompanied by
4162 subprocess termination and SIGCHLD. */
4163 else if (nread == 0 && !NETCONN_P (proc))
4165 #endif /* O_NDELAY */
4166 #endif /* O_NONBLOCK */
4167 #ifdef HAVE_PTYS
4168 /* On some OSs with ptys, when the process on one end of
4169 a pty exits, the other end gets an error reading with
4170 errno = EIO instead of getting an EOF (0 bytes read).
4171 Therefore, if we get an error reading and errno =
4172 EIO, just continue, because the child process has
4173 exited and should clean itself up soon (e.g. when we
4174 get a SIGCHLD).
4176 However, it has been known to happen that the SIGCHLD
4177 got lost. So raise the signl again just in case.
4178 It can't hurt. */
4179 else if (nread == -1 && errno == EIO)
4180 kill (getpid (), SIGCHLD);
4181 #endif /* HAVE_PTYS */
4182 /* If we can detect process termination, don't consider the process
4183 gone just because its pipe is closed. */
4184 #ifdef SIGCHLD
4185 else if (nread == 0 && !NETCONN_P (proc))
4187 #endif
4188 else
4190 /* Preserve status of processes already terminated. */
4191 XSETINT (XPROCESS (proc)->tick, ++process_tick);
4192 deactivate_process (proc);
4193 if (!NILP (XPROCESS (proc)->raw_status_low))
4194 update_status (XPROCESS (proc));
4195 if (EQ (XPROCESS (proc)->status, Qrun))
4196 XPROCESS (proc)->status
4197 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4200 #ifdef NON_BLOCKING_CONNECT
4201 if (check_connect && FD_ISSET (channel, &Connecting))
4203 struct Lisp_Process *p;
4205 FD_CLR (channel, &connect_wait_mask);
4206 if (--num_pending_connects < 0)
4207 abort ();
4209 proc = chan_process[channel];
4210 if (NILP (proc))
4211 continue;
4213 p = XPROCESS (proc);
4215 #ifdef GNU_LINUX
4216 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4217 So only use it on systems where it is known to work. */
4219 int xlen = sizeof(xerrno);
4220 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4221 xerrno = errno;
4223 #else
4225 struct sockaddr pname;
4226 int pnamelen = sizeof(pname);
4228 /* If connection failed, getpeername will fail. */
4229 xerrno = 0;
4230 if (getpeername(channel, &pname, &pnamelen) < 0)
4232 /* Obtain connect failure code through error slippage. */
4233 char dummy;
4234 xerrno = errno;
4235 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
4236 xerrno = errno;
4239 #endif
4240 if (xerrno)
4242 XSETINT (p->tick, ++process_tick);
4243 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
4244 deactivate_process (proc);
4246 else
4248 p->status = Qrun;
4249 /* Execute the sentinel here. If we had relied on
4250 status_notify to do it later, it will read input
4251 from the process before calling the sentinel. */
4252 exec_sentinel (proc, build_string ("open\n"));
4253 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4255 FD_SET (XINT (p->infd), &input_wait_mask);
4256 FD_SET (XINT (p->infd), &non_keyboard_wait_mask);
4260 #endif /* NON_BLOCKING_CONNECT */
4261 } /* end for each file descriptor */
4262 } /* end while exit conditions not met */
4264 waiting_for_user_input_p = 0;
4266 /* If calling from keyboard input, do not quit
4267 since we want to return C-g as an input character.
4268 Otherwise, do pending quit if requested. */
4269 if (XINT (read_kbd) >= 0)
4271 /* Prevent input_pending from remaining set if we quit. */
4272 clear_input_pending ();
4273 QUIT;
4275 #ifdef hpux
4276 /* AlainF 5-Jul-1996
4277 HP-UX 10.10 seems to have problems with signals coming in
4278 Causes "poll: interrupted system call" messages when Emacs is run
4279 in an X window
4280 Turn periodic alarms back on */
4281 start_polling ();
4282 #endif
4284 return got_some_input;
4287 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4289 static Lisp_Object
4290 read_process_output_call (fun_and_args)
4291 Lisp_Object fun_and_args;
4293 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4296 static Lisp_Object
4297 read_process_output_error_handler (error)
4298 Lisp_Object error;
4300 cmd_error_internal (error, "error in process filter: ");
4301 Vinhibit_quit = Qt;
4302 update_echo_area ();
4303 Fsleep_for (make_number (2), Qnil);
4304 return Qt;
4307 /* Read pending output from the process channel,
4308 starting with our buffered-ahead character if we have one.
4309 Yield number of decoded characters read.
4311 This function reads at most 1024 characters.
4312 If you want to read all available subprocess output,
4313 you must call it repeatedly until it returns zero.
4315 The characters read are decoded according to PROC's coding-system
4316 for decoding. */
4319 read_process_output (proc, channel)
4320 Lisp_Object proc;
4321 register int channel;
4323 register int nchars, nbytes;
4324 char *chars;
4325 register Lisp_Object outstream;
4326 register struct buffer *old = current_buffer;
4327 register struct Lisp_Process *p = XPROCESS (proc);
4328 register int opoint;
4329 struct coding_system *coding = proc_decode_coding_system[channel];
4330 int carryover = XINT (p->decoding_carryover);
4331 int readmax = 1024;
4333 #ifdef VMS
4334 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
4336 vs = get_vms_process_pointer (p->pid);
4337 if (vs)
4339 if (!vs->iosb[0])
4340 return (0); /* Really weird if it does this */
4341 if (!(vs->iosb[0] & 1))
4342 return -1; /* I/O error */
4344 else
4345 error ("Could not get VMS process pointer");
4346 chars = vs->inputBuffer;
4347 nbytes = clean_vms_buffer (chars, vs->iosb[1]);
4348 if (nbytes <= 0)
4350 start_vms_process_read (vs); /* Crank up the next read on the process */
4351 return 1; /* Nothing worth printing, say we got 1 */
4353 if (carryover > 0)
4355 /* The data carried over in the previous decoding (which are at
4356 the tail of decoding buffer) should be prepended to the new
4357 data read to decode all together. */
4358 chars = (char *) alloca (nbytes + carryover);
4359 bcopy (SDATA (p->decoding_buf), buf, carryover);
4360 bcopy (vs->inputBuffer, chars + carryover, nbytes);
4362 #else /* not VMS */
4364 #ifdef DATAGRAM_SOCKETS
4365 /* A datagram is one packet; allow at least 1500+ bytes of data
4366 corresponding to the typical Ethernet frame size. */
4367 if (DATAGRAM_CHAN_P (channel))
4369 /* carryover = 0; */ /* Does carryover make sense for datagrams? */
4370 readmax += 1024;
4372 #endif
4374 chars = (char *) alloca (carryover + readmax);
4375 if (carryover)
4376 /* See the comment above. */
4377 bcopy (SDATA (p->decoding_buf), chars, carryover);
4379 #ifdef DATAGRAM_SOCKETS
4380 /* We have a working select, so proc_buffered_char is always -1. */
4381 if (DATAGRAM_CHAN_P (channel))
4383 int len = datagram_address[channel].len;
4384 nbytes = recvfrom (channel, chars + carryover, readmax - carryover,
4385 0, datagram_address[channel].sa, &len);
4387 else
4388 #endif
4389 if (proc_buffered_char[channel] < 0)
4390 nbytes = emacs_read (channel, chars + carryover, readmax - carryover);
4391 else
4393 chars[carryover] = proc_buffered_char[channel];
4394 proc_buffered_char[channel] = -1;
4395 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1 - carryover);
4396 if (nbytes < 0)
4397 nbytes = 1;
4398 else
4399 nbytes = nbytes + 1;
4401 #endif /* not VMS */
4403 XSETINT (p->decoding_carryover, 0);
4405 /* At this point, NBYTES holds number of bytes just received
4406 (including the one in proc_buffered_char[channel]). */
4407 if (nbytes <= 0)
4409 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
4410 return nbytes;
4411 coding->mode |= CODING_MODE_LAST_BLOCK;
4414 /* Now set NBYTES how many bytes we must decode. */
4415 nbytes += carryover;
4417 /* Read and dispose of the process output. */
4418 outstream = p->filter;
4419 if (!NILP (outstream))
4421 /* We inhibit quit here instead of just catching it so that
4422 hitting ^G when a filter happens to be running won't screw
4423 it up. */
4424 int count = SPECPDL_INDEX ();
4425 Lisp_Object odeactivate;
4426 Lisp_Object obuffer, okeymap;
4427 Lisp_Object text;
4428 int outer_running_asynch_code = running_asynch_code;
4429 int waiting = waiting_for_user_input_p;
4431 /* No need to gcpro these, because all we do with them later
4432 is test them for EQness, and none of them should be a string. */
4433 odeactivate = Vdeactivate_mark;
4434 XSETBUFFER (obuffer, current_buffer);
4435 okeymap = current_buffer->keymap;
4437 specbind (Qinhibit_quit, Qt);
4438 specbind (Qlast_nonmenu_event, Qt);
4440 /* In case we get recursively called,
4441 and we already saved the match data nonrecursively,
4442 save the same match data in safely recursive fashion. */
4443 if (outer_running_asynch_code)
4445 Lisp_Object tem;
4446 /* Don't clobber the CURRENT match data, either! */
4447 tem = Fmatch_data (Qnil, Qnil);
4448 restore_match_data ();
4449 record_unwind_protect (Fset_match_data, Fmatch_data (Qnil, Qnil));
4450 Fset_match_data (tem);
4453 /* For speed, if a search happens within this code,
4454 save the match data in a special nonrecursive fashion. */
4455 running_asynch_code = 1;
4457 text = decode_coding_string (make_unibyte_string (chars, nbytes),
4458 coding, 0);
4459 if (NILP (buffer_defaults.enable_multibyte_characters))
4460 /* We had better return unibyte string. */
4461 text = string_make_unibyte (text);
4463 Vlast_coding_system_used = coding->symbol;
4464 /* A new coding system might be found. */
4465 if (!EQ (p->decode_coding_system, coding->symbol))
4467 p->decode_coding_system = coding->symbol;
4469 /* Don't call setup_coding_system for
4470 proc_decode_coding_system[channel] here. It is done in
4471 detect_coding called via decode_coding above. */
4473 /* If a coding system for encoding is not yet decided, we set
4474 it as the same as coding-system for decoding.
4476 But, before doing that we must check if
4477 proc_encode_coding_system[p->outfd] surely points to a
4478 valid memory because p->outfd will be changed once EOF is
4479 sent to the process. */
4480 if (NILP (p->encode_coding_system)
4481 && proc_encode_coding_system[XINT (p->outfd)])
4483 p->encode_coding_system = coding->symbol;
4484 setup_coding_system (coding->symbol,
4485 proc_encode_coding_system[XINT (p->outfd)]);
4489 carryover = nbytes - coding->consumed;
4490 bcopy (chars + coding->consumed, SDATA (p->decoding_buf),
4491 carryover);
4492 XSETINT (p->decoding_carryover, carryover);
4493 nbytes = SBYTES (text);
4494 nchars = SCHARS (text);
4495 if (nbytes > 0)
4496 internal_condition_case_1 (read_process_output_call,
4497 Fcons (outstream,
4498 Fcons (proc, Fcons (text, Qnil))),
4499 !NILP (Vdebug_on_error) ? Qnil : Qerror,
4500 read_process_output_error_handler);
4502 /* If we saved the match data nonrecursively, restore it now. */
4503 restore_match_data ();
4504 running_asynch_code = outer_running_asynch_code;
4506 /* Handling the process output should not deactivate the mark. */
4507 Vdeactivate_mark = odeactivate;
4509 /* Restore waiting_for_user_input_p as it was
4510 when we were called, in case the filter clobbered it. */
4511 waiting_for_user_input_p = waiting;
4513 #if 0 /* Call record_asynch_buffer_change unconditionally,
4514 because we might have changed minor modes or other things
4515 that affect key bindings. */
4516 if (! EQ (Fcurrent_buffer (), obuffer)
4517 || ! EQ (current_buffer->keymap, okeymap))
4518 #endif
4519 /* But do it only if the caller is actually going to read events.
4520 Otherwise there's no need to make him wake up, and it could
4521 cause trouble (for example it would make Fsit_for return). */
4522 if (waiting_for_user_input_p == -1)
4523 record_asynch_buffer_change ();
4525 #ifdef VMS
4526 start_vms_process_read (vs);
4527 #endif
4528 unbind_to (count, Qnil);
4529 return nchars;
4532 /* If no filter, write into buffer if it isn't dead. */
4533 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
4535 Lisp_Object old_read_only;
4536 int old_begv, old_zv;
4537 int old_begv_byte, old_zv_byte;
4538 Lisp_Object odeactivate;
4539 int before, before_byte;
4540 int opoint_byte;
4541 Lisp_Object text;
4542 struct buffer *b;
4544 odeactivate = Vdeactivate_mark;
4546 Fset_buffer (p->buffer);
4547 opoint = PT;
4548 opoint_byte = PT_BYTE;
4549 old_read_only = current_buffer->read_only;
4550 old_begv = BEGV;
4551 old_zv = ZV;
4552 old_begv_byte = BEGV_BYTE;
4553 old_zv_byte = ZV_BYTE;
4555 current_buffer->read_only = Qnil;
4557 /* Insert new output into buffer
4558 at the current end-of-output marker,
4559 thus preserving logical ordering of input and output. */
4560 if (XMARKER (p->mark)->buffer)
4561 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
4562 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
4563 ZV_BYTE));
4564 else
4565 SET_PT_BOTH (ZV, ZV_BYTE);
4566 before = PT;
4567 before_byte = PT_BYTE;
4569 /* If the output marker is outside of the visible region, save
4570 the restriction and widen. */
4571 if (! (BEGV <= PT && PT <= ZV))
4572 Fwiden ();
4574 text = decode_coding_string (make_unibyte_string (chars, nbytes),
4575 coding, 0);
4576 Vlast_coding_system_used = coding->symbol;
4577 /* A new coding system might be found. See the comment in the
4578 similar code in the previous `if' block. */
4579 if (!EQ (p->decode_coding_system, coding->symbol))
4581 p->decode_coding_system = coding->symbol;
4582 if (NILP (p->encode_coding_system)
4583 && proc_encode_coding_system[XINT (p->outfd)])
4585 p->encode_coding_system = coding->symbol;
4586 setup_coding_system (coding->symbol,
4587 proc_encode_coding_system[XINT (p->outfd)]);
4590 carryover = nbytes - coding->consumed;
4591 bcopy (chars + coding->consumed, SDATA (p->decoding_buf),
4592 carryover);
4593 XSETINT (p->decoding_carryover, carryover);
4594 /* Adjust the multibyteness of TEXT to that of the buffer. */
4595 if (NILP (current_buffer->enable_multibyte_characters)
4596 != ! STRING_MULTIBYTE (text))
4597 text = (STRING_MULTIBYTE (text)
4598 ? Fstring_as_unibyte (text)
4599 : Fstring_as_multibyte (text));
4600 nbytes = SBYTES (text);
4601 nchars = SCHARS (text);
4602 /* Insert before markers in case we are inserting where
4603 the buffer's mark is, and the user's next command is Meta-y. */
4604 insert_from_string_before_markers (text, 0, 0, nchars, nbytes, 0);
4606 /* Make sure the process marker's position is valid when the
4607 process buffer is changed in the signal_after_change above.
4608 W3 is known to do that. */
4609 if (BUFFERP (p->buffer)
4610 && (b = XBUFFER (p->buffer), b != current_buffer))
4611 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
4612 else
4613 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
4615 update_mode_lines++;
4617 /* Make sure opoint and the old restrictions
4618 float ahead of any new text just as point would. */
4619 if (opoint >= before)
4621 opoint += PT - before;
4622 opoint_byte += PT_BYTE - before_byte;
4624 if (old_begv > before)
4626 old_begv += PT - before;
4627 old_begv_byte += PT_BYTE - before_byte;
4629 if (old_zv >= before)
4631 old_zv += PT - before;
4632 old_zv_byte += PT_BYTE - before_byte;
4635 /* If the restriction isn't what it should be, set it. */
4636 if (old_begv != BEGV || old_zv != ZV)
4637 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
4639 /* Handling the process output should not deactivate the mark. */
4640 Vdeactivate_mark = odeactivate;
4642 current_buffer->read_only = old_read_only;
4643 SET_PT_BOTH (opoint, opoint_byte);
4644 set_buffer_internal (old);
4646 #ifdef VMS
4647 start_vms_process_read (vs);
4648 #endif
4649 return nbytes;
4652 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
4653 0, 0, 0,
4654 doc: /* Returns non-nil if emacs is waiting for input from the user.
4655 This is intended for use by asynchronous process output filters and sentinels. */)
4658 return (waiting_for_user_input_p ? Qt : Qnil);
4661 /* Sending data to subprocess */
4663 jmp_buf send_process_frame;
4664 Lisp_Object process_sent_to;
4666 SIGTYPE
4667 send_process_trap ()
4669 #ifdef BSD4_1
4670 sigrelse (SIGPIPE);
4671 sigrelse (SIGALRM);
4672 #endif /* BSD4_1 */
4673 longjmp (send_process_frame, 1);
4676 /* Send some data to process PROC.
4677 BUF is the beginning of the data; LEN is the number of characters.
4678 OBJECT is the Lisp object that the data comes from. If OBJECT is
4679 nil or t, it means that the data comes from C string.
4681 If OBJECT is not nil, the data is encoded by PROC's coding-system
4682 for encoding before it is sent.
4684 This function can evaluate Lisp code and can garbage collect. */
4686 void
4687 send_process (proc, buf, len, object)
4688 volatile Lisp_Object proc;
4689 unsigned char *volatile buf;
4690 volatile int len;
4691 volatile Lisp_Object object;
4693 /* Use volatile to protect variables from being clobbered by longjmp. */
4694 int rv;
4695 struct coding_system *coding;
4696 struct gcpro gcpro1;
4698 GCPRO1 (object);
4700 #ifdef VMS
4701 struct Lisp_Process *p = XPROCESS (proc);
4702 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
4703 #endif /* VMS */
4705 if (! NILP (XPROCESS (proc)->raw_status_low))
4706 update_status (XPROCESS (proc));
4707 if (! EQ (XPROCESS (proc)->status, Qrun))
4708 error ("Process %s not running",
4709 SDATA (XPROCESS (proc)->name));
4710 if (XINT (XPROCESS (proc)->outfd) < 0)
4711 error ("Output file descriptor of %s is closed",
4712 SDATA (XPROCESS (proc)->name));
4714 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
4715 Vlast_coding_system_used = coding->symbol;
4717 if ((STRINGP (object) && STRING_MULTIBYTE (object))
4718 || (BUFFERP (object)
4719 && !NILP (XBUFFER (object)->enable_multibyte_characters))
4720 || EQ (object, Qt))
4722 if (!EQ (coding->symbol, XPROCESS (proc)->encode_coding_system))
4723 /* The coding system for encoding was changed to raw-text
4724 because we sent a unibyte text previously. Now we are
4725 sending a multibyte text, thus we must encode it by the
4726 original coding system specified for the current
4727 process. */
4728 setup_coding_system (XPROCESS (proc)->encode_coding_system, coding);
4729 /* src_multibyte should be set to 1 _after_ a call to
4730 setup_coding_system, since it resets src_multibyte to
4731 zero. */
4732 coding->src_multibyte = 1;
4734 else
4736 /* For sending a unibyte text, character code conversion should
4737 not take place but EOL conversion should. So, setup raw-text
4738 or one of the subsidiary if we have not yet done it. */
4739 if (coding->type != coding_type_raw_text)
4741 if (CODING_REQUIRE_FLUSHING (coding))
4743 /* But, before changing the coding, we must flush out data. */
4744 coding->mode |= CODING_MODE_LAST_BLOCK;
4745 send_process (proc, "", 0, Qt);
4747 coding->src_multibyte = 0;
4748 setup_raw_text_coding_system (coding);
4751 coding->dst_multibyte = 0;
4753 if (CODING_REQUIRE_ENCODING (coding))
4755 int require = encoding_buffer_size (coding, len);
4756 int from_byte = -1, from = -1, to = -1;
4757 unsigned char *temp_buf = NULL;
4759 if (BUFFERP (object))
4761 from_byte = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
4762 from = buf_bytepos_to_charpos (XBUFFER (object), from_byte);
4763 to = buf_bytepos_to_charpos (XBUFFER (object), from_byte + len);
4765 else if (STRINGP (object))
4767 from_byte = buf - SDATA (object);
4768 from = string_byte_to_char (object, from_byte);
4769 to = string_byte_to_char (object, from_byte + len);
4772 if (coding->composing != COMPOSITION_DISABLED)
4774 if (from_byte >= 0)
4775 coding_save_composition (coding, from, to, object);
4776 else
4777 coding->composing = COMPOSITION_DISABLED;
4780 if (SBYTES (XPROCESS (proc)->encoding_buf) < require)
4781 XPROCESS (proc)->encoding_buf = make_uninit_string (require);
4783 if (from_byte >= 0)
4784 buf = (BUFFERP (object)
4785 ? BUF_BYTE_ADDRESS (XBUFFER (object), from_byte)
4786 : SDATA (object) + from_byte);
4788 object = XPROCESS (proc)->encoding_buf;
4789 encode_coding (coding, (char *) buf, SDATA (object),
4790 len, SBYTES (object));
4791 len = coding->produced;
4792 buf = SDATA (object);
4793 if (temp_buf)
4794 xfree (temp_buf);
4797 #ifdef VMS
4798 vs = get_vms_process_pointer (p->pid);
4799 if (vs == 0)
4800 error ("Could not find this process: %x", p->pid);
4801 else if (write_to_vms_process (vs, buf, len))
4803 #else /* not VMS */
4805 if (pty_max_bytes == 0)
4807 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
4808 pty_max_bytes = fpathconf (XFASTINT (XPROCESS (proc)->outfd),
4809 _PC_MAX_CANON);
4810 if (pty_max_bytes < 0)
4811 pty_max_bytes = 250;
4812 #else
4813 pty_max_bytes = 250;
4814 #endif
4815 /* Deduct one, to leave space for the eof. */
4816 pty_max_bytes--;
4819 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
4820 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
4821 when returning with longjmp despite being declared volatile. */
4822 if (!setjmp (send_process_frame))
4824 process_sent_to = proc;
4825 while (len > 0)
4827 int this = len;
4828 SIGTYPE (*old_sigpipe)();
4830 /* Decide how much data we can send in one batch.
4831 Long lines need to be split into multiple batches. */
4832 if (!NILP (XPROCESS (proc)->pty_flag))
4834 /* Starting this at zero is always correct when not the first
4835 iteration because the previous iteration ended by sending C-d.
4836 It may not be correct for the first iteration
4837 if a partial line was sent in a separate send_process call.
4838 If that proves worth handling, we need to save linepos
4839 in the process object. */
4840 int linepos = 0;
4841 unsigned char *ptr = (unsigned char *) buf;
4842 unsigned char *end = (unsigned char *) buf + len;
4844 /* Scan through this text for a line that is too long. */
4845 while (ptr != end && linepos < pty_max_bytes)
4847 if (*ptr == '\n')
4848 linepos = 0;
4849 else
4850 linepos++;
4851 ptr++;
4853 /* If we found one, break the line there
4854 and put in a C-d to force the buffer through. */
4855 this = ptr - buf;
4858 /* Send this batch, using one or more write calls. */
4859 while (this > 0)
4861 int outfd = XINT (XPROCESS (proc)->outfd);
4862 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
4863 #ifdef DATAGRAM_SOCKETS
4864 if (DATAGRAM_CHAN_P (outfd))
4866 rv = sendto (outfd, (char *) buf, this,
4867 0, datagram_address[outfd].sa,
4868 datagram_address[outfd].len);
4869 if (rv < 0 && errno == EMSGSIZE)
4870 report_file_error ("sending datagram", Fcons (proc, Qnil));
4872 else
4873 #endif
4874 rv = emacs_write (outfd, (char *) buf, this);
4875 signal (SIGPIPE, old_sigpipe);
4877 if (rv < 0)
4879 if (0
4880 #ifdef EWOULDBLOCK
4881 || errno == EWOULDBLOCK
4882 #endif
4883 #ifdef EAGAIN
4884 || errno == EAGAIN
4885 #endif
4887 /* Buffer is full. Wait, accepting input;
4888 that may allow the program
4889 to finish doing output and read more. */
4891 Lisp_Object zero;
4892 int offset = 0;
4894 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
4895 /* A gross hack to work around a bug in FreeBSD.
4896 In the following sequence, read(2) returns
4897 bogus data:
4899 write(2) 1022 bytes
4900 write(2) 954 bytes, get EAGAIN
4901 read(2) 1024 bytes in process_read_output
4902 read(2) 11 bytes in process_read_output
4904 That is, read(2) returns more bytes than have
4905 ever been written successfully. The 1033 bytes
4906 read are the 1022 bytes written successfully
4907 after processing (for example with CRs added if
4908 the terminal is set up that way which it is
4909 here). The same bytes will be seen again in a
4910 later read(2), without the CRs. */
4912 if (errno == EAGAIN)
4914 int flags = FWRITE;
4915 ioctl (XINT (XPROCESS (proc)->outfd), TIOCFLUSH,
4916 &flags);
4918 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
4920 /* Running filters might relocate buffers or strings.
4921 Arrange to relocate BUF. */
4922 if (BUFFERP (object))
4923 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
4924 else if (STRINGP (object))
4925 offset = buf - SDATA (object);
4927 XSETFASTINT (zero, 0);
4928 #ifdef EMACS_HAS_USECS
4929 wait_reading_process_input (0, 20000, zero, 0);
4930 #else
4931 wait_reading_process_input (1, 0, zero, 0);
4932 #endif
4934 if (BUFFERP (object))
4935 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
4936 else if (STRINGP (object))
4937 buf = offset + SDATA (object);
4939 rv = 0;
4941 else
4942 /* This is a real error. */
4943 report_file_error ("writing to process", Fcons (proc, Qnil));
4945 buf += rv;
4946 len -= rv;
4947 this -= rv;
4950 /* If we sent just part of the string, put in an EOF
4951 to force it through, before we send the rest. */
4952 if (len > 0)
4953 Fprocess_send_eof (proc);
4956 #endif /* not VMS */
4957 else
4959 #ifndef VMS
4960 proc = process_sent_to;
4961 #endif
4962 XPROCESS (proc)->raw_status_low = Qnil;
4963 XPROCESS (proc)->raw_status_high = Qnil;
4964 XPROCESS (proc)->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
4965 XSETINT (XPROCESS (proc)->tick, ++process_tick);
4966 deactivate_process (proc);
4967 #ifdef VMS
4968 error ("Error writing to process %s; closed it",
4969 SDATA (XPROCESS (proc)->name));
4970 #else
4971 error ("SIGPIPE raised on process %s; closed it",
4972 SDATA (XPROCESS (proc)->name));
4973 #endif
4976 UNGCPRO;
4979 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
4980 3, 3, 0,
4981 doc: /* Send current contents of region as input to PROCESS.
4982 PROCESS may be a process, a buffer, the name of a process or buffer, or
4983 nil, indicating the current buffer's process.
4984 Called from program, takes three arguments, PROCESS, START and END.
4985 If the region is more than 500 characters long,
4986 it is sent in several bunches. This may happen even for shorter regions.
4987 Output from processes can arrive in between bunches. */)
4988 (process, start, end)
4989 Lisp_Object process, start, end;
4991 Lisp_Object proc;
4992 int start1, end1;
4994 proc = get_process (process);
4995 validate_region (&start, &end);
4997 if (XINT (start) < GPT && XINT (end) > GPT)
4998 move_gap (XINT (start));
5000 start1 = CHAR_TO_BYTE (XINT (start));
5001 end1 = CHAR_TO_BYTE (XINT (end));
5002 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5003 Fcurrent_buffer ());
5005 return Qnil;
5008 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5009 2, 2, 0,
5010 doc: /* Send PROCESS the contents of STRING as input.
5011 PROCESS may be a process, a buffer, the name of a process or buffer, or
5012 nil, indicating the current buffer's process.
5013 If STRING is more than 500 characters long,
5014 it is sent in several bunches. This may happen even for shorter strings.
5015 Output from processes can arrive in between bunches. */)
5016 (process, string)
5017 Lisp_Object process, string;
5019 Lisp_Object proc;
5020 CHECK_STRING (string);
5021 proc = get_process (process);
5022 send_process (proc, SDATA (string),
5023 SBYTES (string), string);
5024 return Qnil;
5027 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5028 Sprocess_running_child_p, 0, 1, 0,
5029 doc: /* Return t if PROCESS has given the terminal to a child.
5030 If the operating system does not make it possible to find out,
5031 return t unconditionally. */)
5032 (process)
5033 Lisp_Object process;
5035 /* Initialize in case ioctl doesn't exist or gives an error,
5036 in a way that will cause returning t. */
5037 int gid = 0;
5038 Lisp_Object proc;
5039 struct Lisp_Process *p;
5041 proc = get_process (process);
5042 p = XPROCESS (proc);
5044 if (!EQ (p->childp, Qt))
5045 error ("Process %s is not a subprocess",
5046 SDATA (p->name));
5047 if (XINT (p->infd) < 0)
5048 error ("Process %s is not active",
5049 SDATA (p->name));
5051 #ifdef TIOCGPGRP
5052 if (!NILP (p->subtty))
5053 ioctl (XFASTINT (p->subtty), TIOCGPGRP, &gid);
5054 else
5055 ioctl (XINT (p->infd), TIOCGPGRP, &gid);
5056 #endif /* defined (TIOCGPGRP ) */
5058 if (gid == XFASTINT (p->pid))
5059 return Qnil;
5060 return Qt;
5063 /* send a signal number SIGNO to PROCESS.
5064 If CURRENT_GROUP is t, that means send to the process group
5065 that currently owns the terminal being used to communicate with PROCESS.
5066 This is used for various commands in shell mode.
5067 If CURRENT_GROUP is lambda, that means send to the process group
5068 that currently owns the terminal, but only if it is NOT the shell itself.
5070 If NOMSG is zero, insert signal-announcements into process's buffers
5071 right away.
5073 If we can, we try to signal PROCESS by sending control characters
5074 down the pty. This allows us to signal inferiors who have changed
5075 their uid, for which killpg would return an EPERM error. */
5077 static void
5078 process_send_signal (process, signo, current_group, nomsg)
5079 Lisp_Object process;
5080 int signo;
5081 Lisp_Object current_group;
5082 int nomsg;
5084 Lisp_Object proc;
5085 register struct Lisp_Process *p;
5086 int gid;
5087 int no_pgrp = 0;
5089 proc = get_process (process);
5090 p = XPROCESS (proc);
5092 if (!EQ (p->childp, Qt))
5093 error ("Process %s is not a subprocess",
5094 SDATA (p->name));
5095 if (XINT (p->infd) < 0)
5096 error ("Process %s is not active",
5097 SDATA (p->name));
5099 if (NILP (p->pty_flag))
5100 current_group = Qnil;
5102 /* If we are using pgrps, get a pgrp number and make it negative. */
5103 if (NILP (current_group))
5104 /* Send the signal to the shell's process group. */
5105 gid = XFASTINT (p->pid);
5106 else
5108 #ifdef SIGNALS_VIA_CHARACTERS
5109 /* If possible, send signals to the entire pgrp
5110 by sending an input character to it. */
5112 /* TERMIOS is the latest and bestest, and seems most likely to
5113 work. If the system has it, use it. */
5114 #ifdef HAVE_TERMIOS
5115 struct termios t;
5117 switch (signo)
5119 case SIGINT:
5120 tcgetattr (XINT (p->infd), &t);
5121 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5122 return;
5124 case SIGQUIT:
5125 tcgetattr (XINT (p->infd), &t);
5126 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5127 return;
5129 case SIGTSTP:
5130 tcgetattr (XINT (p->infd), &t);
5131 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5132 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5133 #else
5134 send_process (proc, &t.c_cc[VSUSP], 1, Qnil);
5135 #endif
5136 return;
5139 #else /* ! HAVE_TERMIOS */
5141 /* On Berkeley descendants, the following IOCTL's retrieve the
5142 current control characters. */
5143 #if defined (TIOCGLTC) && defined (TIOCGETC)
5145 struct tchars c;
5146 struct ltchars lc;
5148 switch (signo)
5150 case SIGINT:
5151 ioctl (XINT (p->infd), TIOCGETC, &c);
5152 send_process (proc, &c.t_intrc, 1, Qnil);
5153 return;
5154 case SIGQUIT:
5155 ioctl (XINT (p->infd), TIOCGETC, &c);
5156 send_process (proc, &c.t_quitc, 1, Qnil);
5157 return;
5158 #ifdef SIGTSTP
5159 case SIGTSTP:
5160 ioctl (XINT (p->infd), TIOCGLTC, &lc);
5161 send_process (proc, &lc.t_suspc, 1, Qnil);
5162 return;
5163 #endif /* ! defined (SIGTSTP) */
5166 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5168 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
5169 characters. */
5170 #ifdef TCGETA
5171 struct termio t;
5172 switch (signo)
5174 case SIGINT:
5175 ioctl (XINT (p->infd), TCGETA, &t);
5176 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5177 return;
5178 case SIGQUIT:
5179 ioctl (XINT (p->infd), TCGETA, &t);
5180 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5181 return;
5182 #ifdef SIGTSTP
5183 case SIGTSTP:
5184 ioctl (XINT (p->infd), TCGETA, &t);
5185 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5186 return;
5187 #endif /* ! defined (SIGTSTP) */
5189 #else /* ! defined (TCGETA) */
5190 Your configuration files are messed up.
5191 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
5192 you'd better be using one of the alternatives above! */
5193 #endif /* ! defined (TCGETA) */
5194 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5195 #endif /* ! defined HAVE_TERMIOS */
5196 abort ();
5197 /* The code above always returns from the function. */
5198 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5200 #ifdef TIOCGPGRP
5201 /* Get the current pgrp using the tty itself, if we have that.
5202 Otherwise, use the pty to get the pgrp.
5203 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5204 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5205 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5206 His patch indicates that if TIOCGPGRP returns an error, then
5207 we should just assume that p->pid is also the process group id. */
5209 int err;
5211 if (!NILP (p->subtty))
5212 err = ioctl (XFASTINT (p->subtty), TIOCGPGRP, &gid);
5213 else
5214 err = ioctl (XINT (p->infd), TIOCGPGRP, &gid);
5216 if (err == -1)
5217 /* If we can't get the information, assume
5218 the shell owns the tty. */
5219 gid = XFASTINT (p->pid);
5222 /* It is not clear whether anything really can set GID to -1.
5223 Perhaps on some system one of those ioctls can or could do so.
5224 Or perhaps this is vestigial. */
5225 if (gid == -1)
5226 no_pgrp = 1;
5227 #else /* ! defined (TIOCGPGRP ) */
5228 /* Can't select pgrps on this system, so we know that
5229 the child itself heads the pgrp. */
5230 gid = XFASTINT (p->pid);
5231 #endif /* ! defined (TIOCGPGRP ) */
5233 /* If current_group is lambda, and the shell owns the terminal,
5234 don't send any signal. */
5235 if (EQ (current_group, Qlambda) && gid == XFASTINT (p->pid))
5236 return;
5239 switch (signo)
5241 #ifdef SIGCONT
5242 case SIGCONT:
5243 p->raw_status_low = Qnil;
5244 p->raw_status_high = Qnil;
5245 p->status = Qrun;
5246 XSETINT (p->tick, ++process_tick);
5247 if (!nomsg)
5248 status_notify ();
5249 break;
5250 #endif /* ! defined (SIGCONT) */
5251 case SIGINT:
5252 #ifdef VMS
5253 send_process (proc, "\003", 1, Qnil); /* ^C */
5254 goto whoosh;
5255 #endif
5256 case SIGQUIT:
5257 #ifdef VMS
5258 send_process (proc, "\031", 1, Qnil); /* ^Y */
5259 goto whoosh;
5260 #endif
5261 case SIGKILL:
5262 #ifdef VMS
5263 sys$forcex (&(XFASTINT (p->pid)), 0, 1);
5264 whoosh:
5265 #endif
5266 flush_pending_output (XINT (p->infd));
5267 break;
5270 /* If we don't have process groups, send the signal to the immediate
5271 subprocess. That isn't really right, but it's better than any
5272 obvious alternative. */
5273 if (no_pgrp)
5275 kill (XFASTINT (p->pid), signo);
5276 return;
5279 /* gid may be a pid, or minus a pgrp's number */
5280 #ifdef TIOCSIGSEND
5281 if (!NILP (current_group))
5282 ioctl (XINT (p->infd), TIOCSIGSEND, signo);
5283 else
5285 gid = - XFASTINT (p->pid);
5286 kill (gid, signo);
5288 #else /* ! defined (TIOCSIGSEND) */
5289 EMACS_KILLPG (gid, signo);
5290 #endif /* ! defined (TIOCSIGSEND) */
5293 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5294 doc: /* Interrupt process PROCESS.
5295 PROCESS may be a process, a buffer, or the name of a process or buffer.
5296 nil or no arg means current buffer's process.
5297 Second arg CURRENT-GROUP non-nil means send signal to
5298 the current process-group of the process's controlling terminal
5299 rather than to the process's own process group.
5300 If the process is a shell, this means interrupt current subjob
5301 rather than the shell.
5303 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5304 don't send the signal. */)
5305 (process, current_group)
5306 Lisp_Object process, current_group;
5308 process_send_signal (process, SIGINT, current_group, 0);
5309 return process;
5312 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5313 doc: /* Kill process PROCESS. May be process or name of one.
5314 See function `interrupt-process' for more details on usage. */)
5315 (process, current_group)
5316 Lisp_Object process, current_group;
5318 process_send_signal (process, SIGKILL, current_group, 0);
5319 return process;
5322 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5323 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5324 See function `interrupt-process' for more details on usage. */)
5325 (process, current_group)
5326 Lisp_Object process, current_group;
5328 process_send_signal (process, SIGQUIT, current_group, 0);
5329 return process;
5332 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5333 doc: /* Stop process PROCESS. May be process or name of one.
5334 See function `interrupt-process' for more details on usage.
5335 If PROCESS is a network process, inhibit handling of incoming traffic. */)
5336 (process, current_group)
5337 Lisp_Object process, current_group;
5339 #ifdef HAVE_SOCKETS
5340 if (PROCESSP (process) && NETCONN_P (process))
5342 struct Lisp_Process *p;
5344 p = XPROCESS (process);
5345 if (NILP (p->command)
5346 && XINT (p->infd) >= 0)
5348 FD_CLR (XINT (p->infd), &input_wait_mask);
5349 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
5351 p->command = Qt;
5352 return process;
5354 #endif
5355 #ifndef SIGTSTP
5356 error ("no SIGTSTP support");
5357 #else
5358 process_send_signal (process, SIGTSTP, current_group, 0);
5359 #endif
5360 return process;
5363 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5364 doc: /* Continue process PROCESS. May be process or name of one.
5365 See function `interrupt-process' for more details on usage.
5366 If PROCESS is a network process, resume handling of incoming traffic. */)
5367 (process, current_group)
5368 Lisp_Object process, current_group;
5370 #ifdef HAVE_SOCKETS
5371 if (PROCESSP (process) && NETCONN_P (process))
5373 struct Lisp_Process *p;
5375 p = XPROCESS (process);
5376 if (EQ (p->command, Qt)
5377 && XINT (p->infd) >= 0
5378 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5380 FD_SET (XINT (p->infd), &input_wait_mask);
5381 FD_SET (XINT (p->infd), &non_keyboard_wait_mask);
5383 p->command = Qnil;
5384 return process;
5386 #endif
5387 #ifdef SIGCONT
5388 process_send_signal (process, SIGCONT, current_group, 0);
5389 #else
5390 error ("no SIGCONT support");
5391 #endif
5392 return process;
5395 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5396 2, 2, "sProcess (name or number): \nnSignal code: ",
5397 doc: /* Send PROCESS the signal with code SIGCODE.
5398 PROCESS may also be an integer specifying the process id of the
5399 process to signal; in this case, the process need not be a child of
5400 this Emacs.
5401 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5402 (process, sigcode)
5403 Lisp_Object process, sigcode;
5405 Lisp_Object pid;
5407 if (INTEGERP (process))
5409 pid = process;
5410 goto got_it;
5413 if (STRINGP (process))
5415 Lisp_Object tem;
5416 if (tem = Fget_process (process), NILP (tem))
5418 pid = Fstring_to_number (process, make_number (10));
5419 if (XINT (pid) != 0)
5420 goto got_it;
5422 process = tem;
5424 else
5425 process = get_process (process);
5427 if (NILP (process))
5428 return process;
5430 CHECK_PROCESS (process);
5431 pid = XPROCESS (process)->pid;
5432 if (!INTEGERP (pid) || XINT (pid) <= 0)
5433 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5435 got_it:
5437 #define handle_signal(NAME, VALUE) \
5438 else if (!strcmp (name, NAME)) \
5439 XSETINT (sigcode, VALUE)
5441 if (INTEGERP (sigcode))
5443 else
5445 unsigned char *name;
5447 CHECK_SYMBOL (sigcode);
5448 name = SDATA (SYMBOL_NAME (sigcode));
5450 if (0)
5452 #ifdef SIGHUP
5453 handle_signal ("SIGHUP", SIGHUP);
5454 #endif
5455 #ifdef SIGINT
5456 handle_signal ("SIGINT", SIGINT);
5457 #endif
5458 #ifdef SIGQUIT
5459 handle_signal ("SIGQUIT", SIGQUIT);
5460 #endif
5461 #ifdef SIGILL
5462 handle_signal ("SIGILL", SIGILL);
5463 #endif
5464 #ifdef SIGABRT
5465 handle_signal ("SIGABRT", SIGABRT);
5466 #endif
5467 #ifdef SIGEMT
5468 handle_signal ("SIGEMT", SIGEMT);
5469 #endif
5470 #ifdef SIGKILL
5471 handle_signal ("SIGKILL", SIGKILL);
5472 #endif
5473 #ifdef SIGFPE
5474 handle_signal ("SIGFPE", SIGFPE);
5475 #endif
5476 #ifdef SIGBUS
5477 handle_signal ("SIGBUS", SIGBUS);
5478 #endif
5479 #ifdef SIGSEGV
5480 handle_signal ("SIGSEGV", SIGSEGV);
5481 #endif
5482 #ifdef SIGSYS
5483 handle_signal ("SIGSYS", SIGSYS);
5484 #endif
5485 #ifdef SIGPIPE
5486 handle_signal ("SIGPIPE", SIGPIPE);
5487 #endif
5488 #ifdef SIGALRM
5489 handle_signal ("SIGALRM", SIGALRM);
5490 #endif
5491 #ifdef SIGTERM
5492 handle_signal ("SIGTERM", SIGTERM);
5493 #endif
5494 #ifdef SIGURG
5495 handle_signal ("SIGURG", SIGURG);
5496 #endif
5497 #ifdef SIGSTOP
5498 handle_signal ("SIGSTOP", SIGSTOP);
5499 #endif
5500 #ifdef SIGTSTP
5501 handle_signal ("SIGTSTP", SIGTSTP);
5502 #endif
5503 #ifdef SIGCONT
5504 handle_signal ("SIGCONT", SIGCONT);
5505 #endif
5506 #ifdef SIGCHLD
5507 handle_signal ("SIGCHLD", SIGCHLD);
5508 #endif
5509 #ifdef SIGTTIN
5510 handle_signal ("SIGTTIN", SIGTTIN);
5511 #endif
5512 #ifdef SIGTTOU
5513 handle_signal ("SIGTTOU", SIGTTOU);
5514 #endif
5515 #ifdef SIGIO
5516 handle_signal ("SIGIO", SIGIO);
5517 #endif
5518 #ifdef SIGXCPU
5519 handle_signal ("SIGXCPU", SIGXCPU);
5520 #endif
5521 #ifdef SIGXFSZ
5522 handle_signal ("SIGXFSZ", SIGXFSZ);
5523 #endif
5524 #ifdef SIGVTALRM
5525 handle_signal ("SIGVTALRM", SIGVTALRM);
5526 #endif
5527 #ifdef SIGPROF
5528 handle_signal ("SIGPROF", SIGPROF);
5529 #endif
5530 #ifdef SIGWINCH
5531 handle_signal ("SIGWINCH", SIGWINCH);
5532 #endif
5533 #ifdef SIGINFO
5534 handle_signal ("SIGINFO", SIGINFO);
5535 #endif
5536 #ifdef SIGUSR1
5537 handle_signal ("SIGUSR1", SIGUSR1);
5538 #endif
5539 #ifdef SIGUSR2
5540 handle_signal ("SIGUSR2", SIGUSR2);
5541 #endif
5542 else
5543 error ("Undefined signal name %s", name);
5546 #undef handle_signal
5548 return make_number (kill (XINT (pid), XINT (sigcode)));
5551 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
5552 doc: /* Make PROCESS see end-of-file in its input.
5553 EOF comes after any text already sent to it.
5554 PROCESS may be a process, a buffer, the name of a process or buffer, or
5555 nil, indicating the current buffer's process.
5556 If PROCESS is a network connection, or is a process communicating
5557 through a pipe (as opposed to a pty), then you cannot send any more
5558 text to PROCESS after you call this function. */)
5559 (process)
5560 Lisp_Object process;
5562 Lisp_Object proc;
5563 struct coding_system *coding;
5565 if (DATAGRAM_CONN_P (process))
5566 return process;
5568 proc = get_process (process);
5569 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
5571 /* Make sure the process is really alive. */
5572 if (! NILP (XPROCESS (proc)->raw_status_low))
5573 update_status (XPROCESS (proc));
5574 if (! EQ (XPROCESS (proc)->status, Qrun))
5575 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
5577 if (CODING_REQUIRE_FLUSHING (coding))
5579 coding->mode |= CODING_MODE_LAST_BLOCK;
5580 send_process (proc, "", 0, Qnil);
5583 #ifdef VMS
5584 send_process (proc, "\032", 1, Qnil); /* ^z */
5585 #else
5586 if (!NILP (XPROCESS (proc)->pty_flag))
5587 send_process (proc, "\004", 1, Qnil);
5588 else
5590 int old_outfd, new_outfd;
5592 #ifdef HAVE_SHUTDOWN
5593 /* If this is a network connection, or socketpair is used
5594 for communication with the subprocess, call shutdown to cause EOF.
5595 (In some old system, shutdown to socketpair doesn't work.
5596 Then we just can't win.) */
5597 if (NILP (XPROCESS (proc)->pid)
5598 || XINT (XPROCESS (proc)->outfd) == XINT (XPROCESS (proc)->infd))
5599 shutdown (XINT (XPROCESS (proc)->outfd), 1);
5600 /* In case of socketpair, outfd == infd, so don't close it. */
5601 if (XINT (XPROCESS (proc)->outfd) != XINT (XPROCESS (proc)->infd))
5602 emacs_close (XINT (XPROCESS (proc)->outfd));
5603 #else /* not HAVE_SHUTDOWN */
5604 emacs_close (XINT (XPROCESS (proc)->outfd));
5605 #endif /* not HAVE_SHUTDOWN */
5606 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
5607 old_outfd = XINT (XPROCESS (proc)->outfd);
5609 if (!proc_encode_coding_system[new_outfd])
5610 proc_encode_coding_system[new_outfd]
5611 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
5612 bcopy (proc_encode_coding_system[old_outfd],
5613 proc_encode_coding_system[new_outfd],
5614 sizeof (struct coding_system));
5615 bzero (proc_encode_coding_system[old_outfd],
5616 sizeof (struct coding_system));
5618 XSETINT (XPROCESS (proc)->outfd, new_outfd);
5620 #endif /* VMS */
5621 return process;
5624 /* Kill all processes associated with `buffer'.
5625 If `buffer' is nil, kill all processes */
5627 void
5628 kill_buffer_processes (buffer)
5629 Lisp_Object buffer;
5631 Lisp_Object tail, proc;
5633 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
5635 proc = XCDR (XCAR (tail));
5636 if (GC_PROCESSP (proc)
5637 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
5639 if (NETCONN_P (proc))
5640 Fdelete_process (proc);
5641 else if (XINT (XPROCESS (proc)->infd) >= 0)
5642 process_send_signal (proc, SIGHUP, Qnil, 1);
5647 /* On receipt of a signal that a child status has changed, loop asking
5648 about children with changed statuses until the system says there
5649 are no more.
5651 All we do is change the status; we do not run sentinels or print
5652 notifications. That is saved for the next time keyboard input is
5653 done, in order to avoid timing errors.
5655 ** WARNING: this can be called during garbage collection.
5656 Therefore, it must not be fooled by the presence of mark bits in
5657 Lisp objects.
5659 ** USG WARNING: Although it is not obvious from the documentation
5660 in signal(2), on a USG system the SIGCLD handler MUST NOT call
5661 signal() before executing at least one wait(), otherwise the
5662 handler will be called again, resulting in an infinite loop. The
5663 relevant portion of the documentation reads "SIGCLD signals will be
5664 queued and the signal-catching function will be continually
5665 reentered until the queue is empty". Invoking signal() causes the
5666 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
5667 Inc. */
5669 SIGTYPE
5670 sigchld_handler (signo)
5671 int signo;
5673 int old_errno = errno;
5674 Lisp_Object proc;
5675 register struct Lisp_Process *p;
5676 extern EMACS_TIME *input_available_clear_time;
5678 #ifdef BSD4_1
5679 extern int sigheld;
5680 sigheld |= sigbit (SIGCHLD);
5681 #endif
5683 while (1)
5685 register int pid;
5686 WAITTYPE w;
5687 Lisp_Object tail;
5689 #ifdef WNOHANG
5690 #ifndef WUNTRACED
5691 #define WUNTRACED 0
5692 #endif /* no WUNTRACED */
5693 /* Keep trying to get a status until we get a definitive result. */
5696 errno = 0;
5697 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
5699 while (pid < 0 && errno == EINTR);
5701 if (pid <= 0)
5703 /* PID == 0 means no processes found, PID == -1 means a real
5704 failure. We have done all our job, so return. */
5706 /* USG systems forget handlers when they are used;
5707 must reestablish each time */
5708 #if defined (USG) && !defined (POSIX_SIGNALS)
5709 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
5710 #endif
5711 #ifdef BSD4_1
5712 sigheld &= ~sigbit (SIGCHLD);
5713 sigrelse (SIGCHLD);
5714 #endif
5715 errno = old_errno;
5716 return;
5718 #else
5719 pid = wait (&w);
5720 #endif /* no WNOHANG */
5722 /* Find the process that signaled us, and record its status. */
5724 p = 0;
5725 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
5727 proc = XCDR (XCAR (tail));
5728 p = XPROCESS (proc);
5729 if (GC_EQ (p->childp, Qt) && XINT (p->pid) == pid)
5730 break;
5731 p = 0;
5734 /* Look for an asynchronous process whose pid hasn't been filled
5735 in yet. */
5736 if (p == 0)
5737 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
5739 proc = XCDR (XCAR (tail));
5740 p = XPROCESS (proc);
5741 if (GC_INTEGERP (p->pid) && XINT (p->pid) == -1)
5742 break;
5743 p = 0;
5746 /* Change the status of the process that was found. */
5747 if (p != 0)
5749 union { int i; WAITTYPE wt; } u;
5750 int clear_desc_flag = 0;
5752 XSETINT (p->tick, ++process_tick);
5753 u.wt = w;
5754 XSETINT (p->raw_status_low, u.i & 0xffff);
5755 XSETINT (p->raw_status_high, u.i >> 16);
5757 /* If process has terminated, stop waiting for its output. */
5758 if ((WIFSIGNALED (w) || WIFEXITED (w))
5759 && XINT (p->infd) >= 0)
5760 clear_desc_flag = 1;
5762 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
5763 if (clear_desc_flag)
5765 FD_CLR (XINT (p->infd), &input_wait_mask);
5766 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
5769 /* Tell wait_reading_process_input that it needs to wake up and
5770 look around. */
5771 if (input_available_clear_time)
5772 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
5775 /* There was no asynchronous process found for that id. Check
5776 if we have a synchronous process. */
5777 else
5779 synch_process_alive = 0;
5781 /* Report the status of the synchronous process. */
5782 if (WIFEXITED (w))
5783 synch_process_retcode = WRETCODE (w);
5784 else if (WIFSIGNALED (w))
5786 int code = WTERMSIG (w);
5787 char *signame;
5789 synchronize_system_messages_locale ();
5790 signame = strsignal (code);
5792 if (signame == 0)
5793 signame = "unknown";
5795 synch_process_death = signame;
5798 /* Tell wait_reading_process_input that it needs to wake up and
5799 look around. */
5800 if (input_available_clear_time)
5801 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
5804 /* On some systems, we must return right away.
5805 If any more processes want to signal us, we will
5806 get another signal.
5807 Otherwise (on systems that have WNOHANG), loop around
5808 to use up all the processes that have something to tell us. */
5809 #if (defined WINDOWSNT \
5810 || (defined USG && !defined GNU_LINUX \
5811 && !(defined HPUX && defined WNOHANG)))
5812 #if defined (USG) && ! defined (POSIX_SIGNALS)
5813 signal (signo, sigchld_handler);
5814 #endif
5815 errno = old_errno;
5816 return;
5817 #endif /* USG, but not HPUX with WNOHANG */
5822 static Lisp_Object
5823 exec_sentinel_unwind (data)
5824 Lisp_Object data;
5826 XPROCESS (XCAR (data))->sentinel = XCDR (data);
5827 return Qnil;
5830 static Lisp_Object
5831 exec_sentinel_error_handler (error)
5832 Lisp_Object error;
5834 cmd_error_internal (error, "error in process sentinel: ");
5835 Vinhibit_quit = Qt;
5836 update_echo_area ();
5837 Fsleep_for (make_number (2), Qnil);
5838 return Qt;
5841 static void
5842 exec_sentinel (proc, reason)
5843 Lisp_Object proc, reason;
5845 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
5846 register struct Lisp_Process *p = XPROCESS (proc);
5847 int count = SPECPDL_INDEX ();
5848 int outer_running_asynch_code = running_asynch_code;
5849 int waiting = waiting_for_user_input_p;
5851 /* No need to gcpro these, because all we do with them later
5852 is test them for EQness, and none of them should be a string. */
5853 odeactivate = Vdeactivate_mark;
5854 XSETBUFFER (obuffer, current_buffer);
5855 okeymap = current_buffer->keymap;
5857 sentinel = p->sentinel;
5858 if (NILP (sentinel))
5859 return;
5861 /* Zilch the sentinel while it's running, to avoid recursive invocations;
5862 assure that it gets restored no matter how the sentinel exits. */
5863 p->sentinel = Qnil;
5864 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
5865 /* Inhibit quit so that random quits don't screw up a running filter. */
5866 specbind (Qinhibit_quit, Qt);
5867 specbind (Qlast_nonmenu_event, Qt);
5869 /* In case we get recursively called,
5870 and we already saved the match data nonrecursively,
5871 save the same match data in safely recursive fashion. */
5872 if (outer_running_asynch_code)
5874 Lisp_Object tem;
5875 tem = Fmatch_data (Qnil, Qnil);
5876 restore_match_data ();
5877 record_unwind_protect (Fset_match_data, Fmatch_data (Qnil, Qnil));
5878 Fset_match_data (tem);
5881 /* For speed, if a search happens within this code,
5882 save the match data in a special nonrecursive fashion. */
5883 running_asynch_code = 1;
5885 internal_condition_case_1 (read_process_output_call,
5886 Fcons (sentinel,
5887 Fcons (proc, Fcons (reason, Qnil))),
5888 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5889 exec_sentinel_error_handler);
5891 /* If we saved the match data nonrecursively, restore it now. */
5892 restore_match_data ();
5893 running_asynch_code = outer_running_asynch_code;
5895 Vdeactivate_mark = odeactivate;
5897 /* Restore waiting_for_user_input_p as it was
5898 when we were called, in case the filter clobbered it. */
5899 waiting_for_user_input_p = waiting;
5901 #if 0
5902 if (! EQ (Fcurrent_buffer (), obuffer)
5903 || ! EQ (current_buffer->keymap, okeymap))
5904 #endif
5905 /* But do it only if the caller is actually going to read events.
5906 Otherwise there's no need to make him wake up, and it could
5907 cause trouble (for example it would make Fsit_for return). */
5908 if (waiting_for_user_input_p == -1)
5909 record_asynch_buffer_change ();
5911 unbind_to (count, Qnil);
5914 /* Report all recent events of a change in process status
5915 (either run the sentinel or output a message).
5916 This is usually done while Emacs is waiting for keyboard input
5917 but can be done at other times. */
5919 void
5920 status_notify ()
5922 register Lisp_Object proc, buffer;
5923 Lisp_Object tail, msg;
5924 struct gcpro gcpro1, gcpro2;
5926 tail = Qnil;
5927 msg = Qnil;
5928 /* We need to gcpro tail; if read_process_output calls a filter
5929 which deletes a process and removes the cons to which tail points
5930 from Vprocess_alist, and then causes a GC, tail is an unprotected
5931 reference. */
5932 GCPRO2 (tail, msg);
5934 /* Set this now, so that if new processes are created by sentinels
5935 that we run, we get called again to handle their status changes. */
5936 update_tick = process_tick;
5938 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
5940 Lisp_Object symbol;
5941 register struct Lisp_Process *p;
5943 proc = Fcdr (Fcar (tail));
5944 p = XPROCESS (proc);
5946 if (XINT (p->tick) != XINT (p->update_tick))
5948 XSETINT (p->update_tick, XINT (p->tick));
5950 /* If process is still active, read any output that remains. */
5951 while (! EQ (p->filter, Qt)
5952 && ! EQ (p->status, Qconnect)
5953 && ! EQ (p->status, Qlisten)
5954 && ! EQ (p->command, Qt) /* Network process not stopped. */
5955 && XINT (p->infd) >= 0
5956 && read_process_output (proc, XINT (p->infd)) > 0);
5958 buffer = p->buffer;
5960 /* Get the text to use for the message. */
5961 if (!NILP (p->raw_status_low))
5962 update_status (p);
5963 msg = status_message (p->status);
5965 /* If process is terminated, deactivate it or delete it. */
5966 symbol = p->status;
5967 if (CONSP (p->status))
5968 symbol = XCAR (p->status);
5970 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
5971 || EQ (symbol, Qclosed))
5973 if (delete_exited_processes)
5974 remove_process (proc);
5975 else
5976 deactivate_process (proc);
5979 /* The actions above may have further incremented p->tick.
5980 So set p->update_tick again
5981 so that an error in the sentinel will not cause
5982 this code to be run again. */
5983 XSETINT (p->update_tick, XINT (p->tick));
5984 /* Now output the message suitably. */
5985 if (!NILP (p->sentinel))
5986 exec_sentinel (proc, msg);
5987 /* Don't bother with a message in the buffer
5988 when a process becomes runnable. */
5989 else if (!EQ (symbol, Qrun) && !NILP (buffer))
5991 Lisp_Object ro, tem;
5992 struct buffer *old = current_buffer;
5993 int opoint, opoint_byte;
5994 int before, before_byte;
5996 ro = XBUFFER (buffer)->read_only;
5998 /* Avoid error if buffer is deleted
5999 (probably that's why the process is dead, too) */
6000 if (NILP (XBUFFER (buffer)->name))
6001 continue;
6002 Fset_buffer (buffer);
6004 opoint = PT;
6005 opoint_byte = PT_BYTE;
6006 /* Insert new output into buffer
6007 at the current end-of-output marker,
6008 thus preserving logical ordering of input and output. */
6009 if (XMARKER (p->mark)->buffer)
6010 Fgoto_char (p->mark);
6011 else
6012 SET_PT_BOTH (ZV, ZV_BYTE);
6014 before = PT;
6015 before_byte = PT_BYTE;
6017 tem = current_buffer->read_only;
6018 current_buffer->read_only = Qnil;
6019 insert_string ("\nProcess ");
6020 Finsert (1, &p->name);
6021 insert_string (" ");
6022 Finsert (1, &msg);
6023 current_buffer->read_only = tem;
6024 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6026 if (opoint >= before)
6027 SET_PT_BOTH (opoint + (PT - before),
6028 opoint_byte + (PT_BYTE - before_byte));
6029 else
6030 SET_PT_BOTH (opoint, opoint_byte);
6032 set_buffer_internal (old);
6035 } /* end for */
6037 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6038 redisplay_preserve_echo_area (13);
6040 UNGCPRO;
6044 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6045 Sset_process_coding_system, 1, 3, 0,
6046 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6047 DECODING will be used to decode subprocess output and ENCODING to
6048 encode subprocess input. */)
6049 (proc, decoding, encoding)
6050 register Lisp_Object proc, decoding, encoding;
6052 register struct Lisp_Process *p;
6054 CHECK_PROCESS (proc);
6055 p = XPROCESS (proc);
6056 if (XINT (p->infd) < 0)
6057 error ("Input file descriptor of %s closed", SDATA (p->name));
6058 if (XINT (p->outfd) < 0)
6059 error ("Output file descriptor of %s closed", SDATA (p->name));
6061 p->decode_coding_system = Fcheck_coding_system (decoding);
6062 p->encode_coding_system = Fcheck_coding_system (encoding);
6063 setup_coding_system (decoding,
6064 proc_decode_coding_system[XINT (p->infd)]);
6065 setup_coding_system (encoding,
6066 proc_encode_coding_system[XINT (p->outfd)]);
6068 return Qnil;
6071 DEFUN ("process-coding-system",
6072 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6073 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6074 (proc)
6075 register Lisp_Object proc;
6077 CHECK_PROCESS (proc);
6078 return Fcons (XPROCESS (proc)->decode_coding_system,
6079 XPROCESS (proc)->encode_coding_system);
6082 /* The first time this is called, assume keyboard input comes from DESC
6083 instead of from where we used to expect it.
6084 Subsequent calls mean assume input keyboard can come from DESC
6085 in addition to other places. */
6087 static int add_keyboard_wait_descriptor_called_flag;
6089 void
6090 add_keyboard_wait_descriptor (desc)
6091 int desc;
6093 if (! add_keyboard_wait_descriptor_called_flag)
6094 FD_CLR (0, &input_wait_mask);
6095 add_keyboard_wait_descriptor_called_flag = 1;
6096 FD_SET (desc, &input_wait_mask);
6097 FD_SET (desc, &non_process_wait_mask);
6098 if (desc > max_keyboard_desc)
6099 max_keyboard_desc = desc;
6102 /* From now on, do not expect DESC to give keyboard input. */
6104 void
6105 delete_keyboard_wait_descriptor (desc)
6106 int desc;
6108 int fd;
6109 int lim = max_keyboard_desc;
6111 FD_CLR (desc, &input_wait_mask);
6112 FD_CLR (desc, &non_process_wait_mask);
6114 if (desc == max_keyboard_desc)
6115 for (fd = 0; fd < lim; fd++)
6116 if (FD_ISSET (fd, &input_wait_mask)
6117 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6118 max_keyboard_desc = fd;
6121 /* Return nonzero if *MASK has a bit set
6122 that corresponds to one of the keyboard input descriptors. */
6125 keyboard_bit_set (mask)
6126 SELECT_TYPE *mask;
6128 int fd;
6130 for (fd = 0; fd <= max_keyboard_desc; fd++)
6131 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6132 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6133 return 1;
6135 return 0;
6138 void
6139 init_process ()
6141 register int i;
6143 #ifdef SIGCHLD
6144 #ifndef CANNOT_DUMP
6145 if (! noninteractive || initialized)
6146 #endif
6147 signal (SIGCHLD, sigchld_handler);
6148 #endif
6150 FD_ZERO (&input_wait_mask);
6151 FD_ZERO (&non_keyboard_wait_mask);
6152 FD_ZERO (&non_process_wait_mask);
6153 max_process_desc = 0;
6155 FD_SET (0, &input_wait_mask);
6157 Vprocess_alist = Qnil;
6158 for (i = 0; i < MAXDESC; i++)
6160 chan_process[i] = Qnil;
6161 proc_buffered_char[i] = -1;
6163 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
6164 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
6165 #ifdef DATAGRAM_SOCKETS
6166 bzero (datagram_address, sizeof datagram_address);
6167 #endif
6169 #ifdef HAVE_SOCKETS
6171 Lisp_Object subfeatures = Qnil;
6172 #define ADD_SUBFEATURE(key, val) \
6173 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
6175 #ifdef NON_BLOCKING_CONNECT
6176 ADD_SUBFEATURE (QCnowait, Qt);
6177 #endif
6178 #ifdef DATAGRAM_SOCKETS
6179 ADD_SUBFEATURE (QCtype, Qdatagram);
6180 #endif
6181 #ifdef HAVE_LOCAL_SOCKETS
6182 ADD_SUBFEATURE (QCfamily, Qlocal);
6183 #endif
6184 #ifdef HAVE_GETSOCKNAME
6185 ADD_SUBFEATURE (QCservice, Qt);
6186 #endif
6187 #if !defined(TERM) && (defined(O_NONBLOCK) || defined(O_NDELAY))
6188 ADD_SUBFEATURE (QCserver, Qt);
6189 #endif
6190 #ifdef SO_BINDTODEVICE
6191 ADD_SUBFEATURE (QCoptions, intern ("bindtodevice"));
6192 #endif
6193 #ifdef SO_BROADCAST
6194 ADD_SUBFEATURE (QCoptions, intern ("broadcast"));
6195 #endif
6196 #ifdef SO_DONTROUTE
6197 ADD_SUBFEATURE (QCoptions, intern ("dontroute"));
6198 #endif
6199 #ifdef SO_KEEPALIVE
6200 ADD_SUBFEATURE (QCoptions, intern ("keepalive"));
6201 #endif
6202 #ifdef SO_LINGER
6203 ADD_SUBFEATURE (QCoptions, intern ("linger"));
6204 #endif
6205 #ifdef SO_OOBINLINE
6206 ADD_SUBFEATURE (QCoptions, intern ("oobinline"));
6207 #endif
6208 #ifdef SO_PRIORITY
6209 ADD_SUBFEATURE (QCoptions, intern ("priority"));
6210 #endif
6211 #ifdef SO_REUSEADDR
6212 ADD_SUBFEATURE (QCoptions, intern ("reuseaddr"));
6213 #endif
6214 Fprovide (intern ("make-network-process"), subfeatures);
6216 #endif /* HAVE_SOCKETS */
6219 void
6220 syms_of_process ()
6222 Qprocessp = intern ("processp");
6223 staticpro (&Qprocessp);
6224 Qrun = intern ("run");
6225 staticpro (&Qrun);
6226 Qstop = intern ("stop");
6227 staticpro (&Qstop);
6228 Qsignal = intern ("signal");
6229 staticpro (&Qsignal);
6231 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
6232 here again.
6234 Qexit = intern ("exit");
6235 staticpro (&Qexit); */
6237 Qopen = intern ("open");
6238 staticpro (&Qopen);
6239 Qclosed = intern ("closed");
6240 staticpro (&Qclosed);
6241 Qconnect = intern ("connect");
6242 staticpro (&Qconnect);
6243 Qfailed = intern ("failed");
6244 staticpro (&Qfailed);
6245 Qlisten = intern ("listen");
6246 staticpro (&Qlisten);
6247 Qlocal = intern ("local");
6248 staticpro (&Qlocal);
6249 Qdatagram = intern ("datagram");
6250 staticpro (&Qdatagram);
6252 QCname = intern (":name");
6253 staticpro (&QCname);
6254 QCbuffer = intern (":buffer");
6255 staticpro (&QCbuffer);
6256 QChost = intern (":host");
6257 staticpro (&QChost);
6258 QCservice = intern (":service");
6259 staticpro (&QCservice);
6260 QCtype = intern (":type");
6261 staticpro (&QCtype);
6262 QClocal = intern (":local");
6263 staticpro (&QClocal);
6264 QCremote = intern (":remote");
6265 staticpro (&QCremote);
6266 QCcoding = intern (":coding");
6267 staticpro (&QCcoding);
6268 QCserver = intern (":server");
6269 staticpro (&QCserver);
6270 QCnowait = intern (":nowait");
6271 staticpro (&QCnowait);
6272 QCsentinel = intern (":sentinel");
6273 staticpro (&QCsentinel);
6274 QClog = intern (":log");
6275 staticpro (&QClog);
6276 QCnoquery = intern (":noquery");
6277 staticpro (&QCnoquery);
6278 QCstop = intern (":stop");
6279 staticpro (&QCstop);
6280 QCoptions = intern (":options");
6281 staticpro (&QCoptions);
6283 Qlast_nonmenu_event = intern ("last-nonmenu-event");
6284 staticpro (&Qlast_nonmenu_event);
6286 staticpro (&Vprocess_alist);
6288 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
6289 doc: /* *Non-nil means delete processes immediately when they exit.
6290 nil means don't delete them until `list-processes' is run. */);
6292 delete_exited_processes = 1;
6294 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
6295 doc: /* Control type of device used to communicate with subprocesses.
6296 Values are nil to use a pipe, or t or `pty' to use a pty.
6297 The value has no effect if the system has no ptys or if all ptys are busy:
6298 then a pipe is used in any case.
6299 The value takes effect when `start-process' is called. */);
6300 Vprocess_connection_type = Qt;
6302 defsubr (&Sprocessp);
6303 defsubr (&Sget_process);
6304 defsubr (&Sget_buffer_process);
6305 defsubr (&Sdelete_process);
6306 defsubr (&Sprocess_status);
6307 defsubr (&Sprocess_exit_status);
6308 defsubr (&Sprocess_id);
6309 defsubr (&Sprocess_name);
6310 defsubr (&Sprocess_tty_name);
6311 defsubr (&Sprocess_command);
6312 defsubr (&Sset_process_buffer);
6313 defsubr (&Sprocess_buffer);
6314 defsubr (&Sprocess_mark);
6315 defsubr (&Sset_process_filter);
6316 defsubr (&Sprocess_filter);
6317 defsubr (&Sset_process_sentinel);
6318 defsubr (&Sprocess_sentinel);
6319 defsubr (&Sset_process_window_size);
6320 defsubr (&Sset_process_inherit_coding_system_flag);
6321 defsubr (&Sprocess_inherit_coding_system_flag);
6322 defsubr (&Sset_process_query_on_exit_flag);
6323 defsubr (&Sprocess_query_on_exit_flag);
6324 defsubr (&Sprocess_contact);
6325 defsubr (&Slist_processes);
6326 defsubr (&Sprocess_list);
6327 defsubr (&Sstart_process);
6328 #ifdef HAVE_SOCKETS
6329 defsubr (&Sset_network_process_options);
6330 defsubr (&Smake_network_process);
6331 defsubr (&Sformat_network_address);
6332 #endif /* HAVE_SOCKETS */
6333 #ifdef DATAGRAM_SOCKETS
6334 defsubr (&Sprocess_datagram_address);
6335 defsubr (&Sset_process_datagram_address);
6336 #endif
6337 defsubr (&Saccept_process_output);
6338 defsubr (&Sprocess_send_region);
6339 defsubr (&Sprocess_send_string);
6340 defsubr (&Sinterrupt_process);
6341 defsubr (&Skill_process);
6342 defsubr (&Squit_process);
6343 defsubr (&Sstop_process);
6344 defsubr (&Scontinue_process);
6345 defsubr (&Sprocess_running_child_p);
6346 defsubr (&Sprocess_send_eof);
6347 defsubr (&Ssignal_process);
6348 defsubr (&Swaiting_for_user_input_p);
6349 /* defsubr (&Sprocess_connection); */
6350 defsubr (&Sset_process_coding_system);
6351 defsubr (&Sprocess_coding_system);
6355 #else /* not subprocesses */
6357 #include <sys/types.h>
6358 #include <errno.h>
6360 #include "lisp.h"
6361 #include "systime.h"
6362 #include "charset.h"
6363 #include "coding.h"
6364 #include "termopts.h"
6365 #include "sysselect.h"
6367 extern int frame_garbaged;
6369 extern EMACS_TIME timer_check ();
6370 extern int timers_run;
6372 Lisp_Object QCtype;
6374 /* As described above, except assuming that there are no subprocesses:
6376 Wait for timeout to elapse and/or keyboard input to be available.
6378 time_limit is:
6379 timeout in seconds, or
6380 zero for no limit, or
6381 -1 means gobble data immediately available but don't wait for any.
6383 read_kbd is a Lisp_Object:
6384 0 to ignore keyboard input, or
6385 1 to return when input is available, or
6386 -1 means caller will actually read the input, so don't throw to
6387 the quit handler.
6388 a cons cell, meaning wait until its car is non-nil
6389 (and gobble terminal input into the buffer if any arrives), or
6390 We know that read_kbd will never be a Lisp_Process, since
6391 `subprocesses' isn't defined.
6393 do_display != 0 means redisplay should be done to show subprocess
6394 output that arrives.
6396 Return true iff we received input from any process. */
6399 wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
6400 int time_limit, microsecs;
6401 Lisp_Object read_kbd;
6402 int do_display;
6404 register int nfds;
6405 EMACS_TIME end_time, timeout;
6406 SELECT_TYPE waitchannels;
6407 int xerrno;
6408 /* Either nil or a cons cell, the car of which is of interest and
6409 may be changed outside of this routine. */
6410 Lisp_Object wait_for_cell;
6412 wait_for_cell = Qnil;
6414 /* If waiting for non-nil in a cell, record where. */
6415 if (CONSP (read_kbd))
6417 wait_for_cell = read_kbd;
6418 XSETFASTINT (read_kbd, 0);
6421 /* What does time_limit really mean? */
6422 if (time_limit || microsecs)
6424 EMACS_GET_TIME (end_time);
6425 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6426 EMACS_ADD_TIME (end_time, end_time, timeout);
6429 /* Turn off periodic alarms (in case they are in use)
6430 and then turn off any other atimers,
6431 because the select emulator uses alarms. */
6432 stop_polling ();
6433 turn_on_atimers (0);
6435 while (1)
6437 int timeout_reduced_for_timers = 0;
6439 /* If calling from keyboard input, do not quit
6440 since we want to return C-g as an input character.
6441 Otherwise, do pending quit if requested. */
6442 if (XINT (read_kbd) >= 0)
6443 QUIT;
6445 /* Exit now if the cell we're waiting for became non-nil. */
6446 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6447 break;
6449 /* Compute time from now till when time limit is up */
6450 /* Exit if already run out */
6451 if (time_limit == -1)
6453 /* -1 specified for timeout means
6454 gobble output available now
6455 but don't wait at all. */
6457 EMACS_SET_SECS_USECS (timeout, 0, 0);
6459 else if (time_limit || microsecs)
6461 EMACS_GET_TIME (timeout);
6462 EMACS_SUB_TIME (timeout, end_time, timeout);
6463 if (EMACS_TIME_NEG_P (timeout))
6464 break;
6466 else
6468 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6471 /* If our caller will not immediately handle keyboard events,
6472 run timer events directly.
6473 (Callers that will immediately read keyboard events
6474 call timer_delay on their own.) */
6475 if (NILP (wait_for_cell))
6477 EMACS_TIME timer_delay;
6481 int old_timers_run = timers_run;
6482 timer_delay = timer_check (1);
6483 if (timers_run != old_timers_run && do_display)
6484 /* We must retry, since a timer may have requeued itself
6485 and that could alter the time delay. */
6486 redisplay_preserve_echo_area (14);
6487 else
6488 break;
6490 while (!detect_input_pending ());
6492 /* If there is unread keyboard input, also return. */
6493 if (XINT (read_kbd) != 0
6494 && requeued_events_pending_p ())
6495 break;
6497 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6499 EMACS_TIME difference;
6500 EMACS_SUB_TIME (difference, timer_delay, timeout);
6501 if (EMACS_TIME_NEG_P (difference))
6503 timeout = timer_delay;
6504 timeout_reduced_for_timers = 1;
6509 /* Cause C-g and alarm signals to take immediate action,
6510 and cause input available signals to zero out timeout. */
6511 if (XINT (read_kbd) < 0)
6512 set_waiting_for_input (&timeout);
6514 /* Wait till there is something to do. */
6516 if (! XINT (read_kbd) && NILP (wait_for_cell))
6517 FD_ZERO (&waitchannels);
6518 else
6519 FD_SET (0, &waitchannels);
6521 /* If a frame has been newly mapped and needs updating,
6522 reprocess its display stuff. */
6523 if (frame_garbaged && do_display)
6525 clear_waiting_for_input ();
6526 redisplay_preserve_echo_area (15);
6527 if (XINT (read_kbd) < 0)
6528 set_waiting_for_input (&timeout);
6531 if (XINT (read_kbd) && detect_input_pending ())
6533 nfds = 0;
6534 FD_ZERO (&waitchannels);
6536 else
6537 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
6538 &timeout);
6540 xerrno = errno;
6542 /* Make C-g and alarm signals set flags again */
6543 clear_waiting_for_input ();
6545 /* If we woke up due to SIGWINCH, actually change size now. */
6546 do_pending_window_change (0);
6548 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
6549 /* We waited the full specified time, so return now. */
6550 break;
6552 if (nfds == -1)
6554 /* If the system call was interrupted, then go around the
6555 loop again. */
6556 if (xerrno == EINTR)
6557 FD_ZERO (&waitchannels);
6558 else
6559 error ("select error: %s", emacs_strerror (xerrno));
6561 #ifdef sun
6562 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
6563 /* System sometimes fails to deliver SIGIO. */
6564 kill (getpid (), SIGIO);
6565 #endif
6566 #ifdef SIGIO
6567 if (XINT (read_kbd) && interrupt_input && (waitchannels & 1))
6568 kill (getpid (), SIGIO);
6569 #endif
6571 /* Check for keyboard input */
6573 if ((XINT (read_kbd) != 0)
6574 && detect_input_pending_run_timers (do_display))
6576 swallow_events (do_display);
6577 if (detect_input_pending_run_timers (do_display))
6578 break;
6581 /* If there is unread keyboard input, also return. */
6582 if (XINT (read_kbd) != 0
6583 && requeued_events_pending_p ())
6584 break;
6586 /* If wait_for_cell. check for keyboard input
6587 but don't run any timers.
6588 ??? (It seems wrong to me to check for keyboard
6589 input at all when wait_for_cell, but the code
6590 has been this way since July 1994.
6591 Try changing this after version 19.31.) */
6592 if (! NILP (wait_for_cell)
6593 && detect_input_pending ())
6595 swallow_events (do_display);
6596 if (detect_input_pending ())
6597 break;
6600 /* Exit now if the cell we're waiting for became non-nil. */
6601 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6602 break;
6605 start_polling ();
6607 return 0;
6611 /* Don't confuse make-docfile by having two doc strings for this function.
6612 make-docfile does not pay attention to #if, for good reason! */
6613 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6615 (name)
6616 register Lisp_Object name;
6618 return Qnil;
6621 /* Don't confuse make-docfile by having two doc strings for this function.
6622 make-docfile does not pay attention to #if, for good reason! */
6623 DEFUN ("process-inherit-coding-system-flag",
6624 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6625 1, 1, 0,
6627 (process)
6628 register Lisp_Object process;
6630 /* Ignore the argument and return the value of
6631 inherit-process-coding-system. */
6632 return inherit_process_coding_system ? Qt : Qnil;
6635 /* Kill all processes associated with `buffer'.
6636 If `buffer' is nil, kill all processes.
6637 Since we have no subprocesses, this does nothing. */
6639 void
6640 kill_buffer_processes (buffer)
6641 Lisp_Object buffer;
6645 void
6646 init_process ()
6650 void
6651 syms_of_process ()
6653 QCtype = intern (":type");
6654 staticpro (&QCtype);
6656 defsubr (&Sget_buffer_process);
6657 defsubr (&Sprocess_inherit_coding_system_flag);
6661 #endif /* not subprocesses */