(hexl-mode-map): Use command remapping instead of
[emacs.git] / src / process.c
blob24782504f05b1099a31499bdce836d4e42a16c45
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, QCvars;
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 property list (KEY VAL ...). */
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 DEFUN ("process-variable", Fprocess_variable, Sprocess_variable,
1041 1, 2, 0,
1042 doc: /* Return the value of PROCESS' private variable VAR.
1043 If VARIABLE is omitted or nil, return plist with all PROCESS variables. */)
1044 (process, var)
1045 register Lisp_Object process, var;
1047 CHECK_PROCESS (process);
1049 if (NILP (var))
1050 return XPROCESS (process)->private_vars;
1052 return Fplist_get (XPROCESS (process)->private_vars, var);
1055 DEFUN ("set-process-variable", Fset_process_variable, Sset_process_variable,
1056 3, 3, 0,
1057 doc: /* Change value of PROCESS' private variable VAR to VAL, and return VAL.
1058 If VAR is nil, set all PROCESS' private variables according to plist VAL. */)
1059 (process, var, val)
1060 register Lisp_Object process, var, val;
1062 CHECK_PROCESS (process);
1064 XPROCESS (process)->private_vars
1065 = (NILP (var)
1066 ? val
1067 : Fplist_put (XPROCESS (process)->private_vars, var, val));
1069 return val;
1072 #if 0 /* Turned off because we don't currently record this info
1073 in the process. Perhaps add it. */
1074 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1075 doc: /* Return the connection type of PROCESS.
1076 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1077 a socket connection. */)
1078 (process)
1079 Lisp_Object process;
1081 return XPROCESS (process)->type;
1083 #endif
1085 #ifdef HAVE_SOCKETS
1086 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1087 1, 2, 0,
1088 doc: /* Convert network ADDRESS from internal format to a string.
1089 If optional second argument OMIT-PORT is non-nil, don't include a port
1090 number in the string; in this case, interpret a 4 element vector as an
1091 IP address. Returns nil if format of ADDRESS is invalid. */)
1092 (address, omit_port)
1093 Lisp_Object address, omit_port;
1095 if (NILP (address))
1096 return Qnil;
1098 if (STRINGP (address)) /* AF_LOCAL */
1099 return address;
1101 if (VECTORP (address)) /* AF_INET */
1103 register struct Lisp_Vector *p = XVECTOR (address);
1104 Lisp_Object args[6];
1105 int nargs, i;
1107 if (!NILP (omit_port) && (p->size == 4 || p->size == 5))
1109 args[0] = build_string ("%d.%d.%d.%d");
1110 nargs = 4;
1112 else if (p->size == 5)
1114 args[0] = build_string ("%d.%d.%d.%d:%d");
1115 nargs = 5;
1117 else
1118 return Qnil;
1120 for (i = 0; i < nargs; i++)
1121 args[i+1] = p->contents[i];
1122 return Fformat (nargs+1, args);
1125 if (CONSP (address))
1127 Lisp_Object args[2];
1128 args[0] = build_string ("<Family %d>");
1129 args[1] = Fcar (address);
1130 return Fformat (2, args);
1134 return Qnil;
1136 #endif
1138 Lisp_Object
1139 list_processes_1 (query_only)
1140 Lisp_Object query_only;
1142 register Lisp_Object tail, tem;
1143 Lisp_Object proc, minspace, tem1;
1144 register struct Lisp_Process *p;
1145 char tembuf[300];
1146 int w_proc, w_buffer, w_tty;
1147 Lisp_Object i_status, i_buffer, i_tty, i_command;
1149 w_proc = 4; /* Proc */
1150 w_buffer = 6; /* Buffer */
1151 w_tty = 0; /* Omit if no ttys */
1153 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
1155 int i;
1157 proc = Fcdr (Fcar (tail));
1158 p = XPROCESS (proc);
1159 if (NILP (p->childp))
1160 continue;
1161 if (!NILP (query_only) && !NILP (p->kill_without_query))
1162 continue;
1163 if (STRINGP (p->name)
1164 && ( i = SCHARS (p->name), (i > w_proc)))
1165 w_proc = i;
1166 if (!NILP (p->buffer))
1168 if (NILP (XBUFFER (p->buffer)->name) && w_buffer < 8)
1169 w_buffer = 8; /* (Killed) */
1170 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1171 w_buffer = i;
1173 if (STRINGP (p->tty_name)
1174 && (i = SCHARS (p->tty_name), (i > w_tty)))
1175 w_tty = i;
1178 XSETFASTINT (i_status, w_proc + 1);
1179 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1180 if (w_tty)
1182 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1183 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_tty + 1);
1184 } else {
1185 i_tty = Qnil;
1186 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1189 XSETFASTINT (minspace, 1);
1191 set_buffer_internal (XBUFFER (Vstandard_output));
1192 Fbuffer_disable_undo (Vstandard_output);
1194 current_buffer->truncate_lines = Qt;
1196 write_string ("Proc", -1);
1197 Findent_to (i_status, minspace); write_string ("Status", -1);
1198 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1199 if (!NILP (i_tty))
1201 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1203 Findent_to (i_command, minspace); write_string ("Command", -1);
1204 write_string ("\n", -1);
1206 write_string ("----", -1);
1207 Findent_to (i_status, minspace); write_string ("------", -1);
1208 Findent_to (i_buffer, minspace); write_string ("------", -1);
1209 if (!NILP (i_tty))
1211 Findent_to (i_tty, minspace); write_string ("---", -1);
1213 Findent_to (i_command, minspace); write_string ("-------", -1);
1214 write_string ("\n", -1);
1216 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
1218 Lisp_Object symbol;
1220 proc = Fcdr (Fcar (tail));
1221 p = XPROCESS (proc);
1222 if (NILP (p->childp))
1223 continue;
1224 if (!NILP (query_only) && !NILP (p->kill_without_query))
1225 continue;
1227 Finsert (1, &p->name);
1228 Findent_to (i_status, minspace);
1230 if (!NILP (p->raw_status_low))
1231 update_status (p);
1232 symbol = p->status;
1233 if (CONSP (p->status))
1234 symbol = XCAR (p->status);
1237 if (EQ (symbol, Qsignal))
1239 Lisp_Object tem;
1240 tem = Fcar (Fcdr (p->status));
1241 #ifdef VMS
1242 if (XINT (tem) < NSIG)
1243 write_string (sys_errlist [XINT (tem)], -1);
1244 else
1245 #endif
1246 Fprinc (symbol, Qnil);
1248 else if (NETCONN1_P (p))
1250 if (EQ (symbol, Qexit))
1251 write_string ("closed", -1);
1252 else if (EQ (p->command, Qt))
1253 write_string ("stopped", -1);
1254 else if (EQ (symbol, Qrun))
1255 write_string ("open", -1);
1256 else
1257 Fprinc (symbol, Qnil);
1259 else
1260 Fprinc (symbol, Qnil);
1262 if (EQ (symbol, Qexit))
1264 Lisp_Object tem;
1265 tem = Fcar (Fcdr (p->status));
1266 if (XFASTINT (tem))
1268 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1269 write_string (tembuf, -1);
1273 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
1274 remove_process (proc);
1276 Findent_to (i_buffer, minspace);
1277 if (NILP (p->buffer))
1278 insert_string ("(none)");
1279 else if (NILP (XBUFFER (p->buffer)->name))
1280 insert_string ("(Killed)");
1281 else
1282 Finsert (1, &XBUFFER (p->buffer)->name);
1284 if (!NILP (i_tty))
1286 Findent_to (i_tty, minspace);
1287 if (STRINGP (p->tty_name))
1288 Finsert (1, &p->tty_name);
1291 Findent_to (i_command, minspace);
1293 if (EQ (p->status, Qlisten))
1295 Lisp_Object port = Fplist_get (p->childp, QCservice);
1296 if (INTEGERP (port))
1297 port = Fnumber_to_string (port);
1298 if (NILP (port))
1299 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1300 sprintf (tembuf, "(network %s server on %s)\n",
1301 (DATAGRAM_CHAN_P (XINT (p->infd)) ? "datagram" : "stream"),
1302 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1303 insert_string (tembuf);
1305 else if (NETCONN1_P (p))
1307 /* For a local socket, there is no host name,
1308 so display service instead. */
1309 Lisp_Object host = Fplist_get (p->childp, QChost);
1310 if (!STRINGP (host))
1312 host = Fplist_get (p->childp, QCservice);
1313 if (INTEGERP (host))
1314 host = Fnumber_to_string (host);
1316 if (NILP (host))
1317 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1318 sprintf (tembuf, "(network %s connection to %s)\n",
1319 (DATAGRAM_CHAN_P (XINT (p->infd)) ? "datagram" : "stream"),
1320 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1321 insert_string (tembuf);
1323 else
1325 tem = p->command;
1326 while (1)
1328 tem1 = Fcar (tem);
1329 Finsert (1, &tem1);
1330 tem = Fcdr (tem);
1331 if (NILP (tem))
1332 break;
1333 insert_string (" ");
1335 insert_string ("\n");
1338 return Qnil;
1341 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1342 doc: /* Display a list of all processes.
1343 If optional argument QUERY-ONLY is non-nil, only processes with
1344 the query-on-exit flag set will be listed.
1345 Any process listed as exited or signaled is actually eliminated
1346 after the listing is made. */)
1347 (query_only)
1348 Lisp_Object query_only;
1350 internal_with_output_to_temp_buffer ("*Process List*",
1351 list_processes_1, query_only);
1352 return Qnil;
1355 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1356 doc: /* Return a list of all processes. */)
1359 return Fmapcar (Qcdr, Vprocess_alist);
1362 /* Starting asynchronous inferior processes. */
1364 static Lisp_Object start_process_unwind ();
1366 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1367 doc: /* Start a program in a subprocess. Return the process object for it.
1368 NAME is name for process. It is modified if necessary to make it unique.
1369 BUFFER is the buffer or (buffer-name) to associate with the process.
1370 Process output goes at end of that buffer, unless you specify
1371 an output stream or filter function to handle the output.
1372 BUFFER may be also nil, meaning that this process is not associated
1373 with any buffer.
1374 Third arg is program file name. It is searched for in PATH.
1375 Remaining arguments are strings to give program as arguments.
1377 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1378 (nargs, args)
1379 int nargs;
1380 register Lisp_Object *args;
1382 Lisp_Object buffer, name, program, proc, current_dir, tem;
1383 #ifdef VMS
1384 register unsigned char *new_argv;
1385 int len;
1386 #else
1387 register unsigned char **new_argv;
1388 #endif
1389 register int i;
1390 int count = SPECPDL_INDEX ();
1392 buffer = args[1];
1393 if (!NILP (buffer))
1394 buffer = Fget_buffer_create (buffer);
1396 /* Make sure that the child will be able to chdir to the current
1397 buffer's current directory, or its unhandled equivalent. We
1398 can't just have the child check for an error when it does the
1399 chdir, since it's in a vfork.
1401 We have to GCPRO around this because Fexpand_file_name and
1402 Funhandled_file_name_directory might call a file name handling
1403 function. The argument list is protected by the caller, so all
1404 we really have to worry about is buffer. */
1406 struct gcpro gcpro1, gcpro2;
1408 current_dir = current_buffer->directory;
1410 GCPRO2 (buffer, current_dir);
1412 current_dir
1413 = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
1414 Qnil);
1415 if (NILP (Ffile_accessible_directory_p (current_dir)))
1416 report_file_error ("Setting current directory",
1417 Fcons (current_buffer->directory, Qnil));
1419 UNGCPRO;
1422 name = args[0];
1423 CHECK_STRING (name);
1425 program = args[2];
1427 CHECK_STRING (program);
1429 proc = make_process (name);
1430 /* If an error occurs and we can't start the process, we want to
1431 remove it from the process list. This means that each error
1432 check in create_process doesn't need to call remove_process
1433 itself; it's all taken care of here. */
1434 record_unwind_protect (start_process_unwind, proc);
1436 XPROCESS (proc)->childp = Qt;
1437 XPROCESS (proc)->private_vars = Qnil;
1438 XPROCESS (proc)->command_channel_p = Qnil;
1439 XPROCESS (proc)->buffer = buffer;
1440 XPROCESS (proc)->sentinel = Qnil;
1441 XPROCESS (proc)->filter = Qnil;
1442 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1444 /* Make the process marker point into the process buffer (if any). */
1445 if (!NILP (buffer))
1446 set_marker_both (XPROCESS (proc)->mark, buffer,
1447 BUF_ZV (XBUFFER (buffer)),
1448 BUF_ZV_BYTE (XBUFFER (buffer)));
1451 /* Decide coding systems for communicating with the process. Here
1452 we don't setup the structure coding_system nor pay attention to
1453 unibyte mode. They are done in create_process. */
1455 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1456 Lisp_Object coding_systems = Qt;
1457 Lisp_Object val, *args2;
1458 struct gcpro gcpro1, gcpro2;
1460 val = Vcoding_system_for_read;
1461 if (NILP (val))
1463 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1464 args2[0] = Qstart_process;
1465 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1466 GCPRO2 (proc, current_dir);
1467 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1468 UNGCPRO;
1469 if (CONSP (coding_systems))
1470 val = XCAR (coding_systems);
1471 else if (CONSP (Vdefault_process_coding_system))
1472 val = XCAR (Vdefault_process_coding_system);
1474 XPROCESS (proc)->decode_coding_system = val;
1476 val = Vcoding_system_for_write;
1477 if (NILP (val))
1479 if (EQ (coding_systems, Qt))
1481 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1482 args2[0] = Qstart_process;
1483 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1484 GCPRO2 (proc, current_dir);
1485 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1486 UNGCPRO;
1488 if (CONSP (coding_systems))
1489 val = XCDR (coding_systems);
1490 else if (CONSP (Vdefault_process_coding_system))
1491 val = XCDR (Vdefault_process_coding_system);
1493 XPROCESS (proc)->encode_coding_system = val;
1496 #ifdef VMS
1497 /* Make a one member argv with all args concatenated
1498 together separated by a blank. */
1499 len = SBYTES (program) + 2;
1500 for (i = 3; i < nargs; i++)
1502 tem = args[i];
1503 CHECK_STRING (tem);
1504 len += SBYTES (tem) + 1; /* count the blank */
1506 new_argv = (unsigned char *) alloca (len);
1507 strcpy (new_argv, SDATA (program));
1508 for (i = 3; i < nargs; i++)
1510 tem = args[i];
1511 CHECK_STRING (tem);
1512 strcat (new_argv, " ");
1513 strcat (new_argv, SDATA (tem));
1515 /* Need to add code here to check for program existence on VMS */
1517 #else /* not VMS */
1518 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1520 /* If program file name is not absolute, search our path for it.
1521 Put the name we will really use in TEM. */
1522 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1523 && !(SCHARS (program) > 1
1524 && IS_DEVICE_SEP (SREF (program, 1))))
1526 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1528 tem = Qnil;
1529 GCPRO4 (name, program, buffer, current_dir);
1530 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1531 UNGCPRO;
1532 if (NILP (tem))
1533 report_file_error ("Searching for program", Fcons (program, Qnil));
1534 tem = Fexpand_file_name (tem, Qnil);
1536 else
1538 if (!NILP (Ffile_directory_p (program)))
1539 error ("Specified program for new process is a directory");
1540 tem = program;
1543 /* If program file name starts with /: for quoting a magic name,
1544 discard that. */
1545 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1546 && SREF (tem, 1) == ':')
1547 tem = Fsubstring (tem, make_number (2), Qnil);
1549 /* Encode the file name and put it in NEW_ARGV.
1550 That's where the child will use it to execute the program. */
1551 tem = ENCODE_FILE (tem);
1552 new_argv[0] = SDATA (tem);
1554 /* Here we encode arguments by the coding system used for sending
1555 data to the process. We don't support using different coding
1556 systems for encoding arguments and for encoding data sent to the
1557 process. */
1559 for (i = 3; i < nargs; i++)
1561 tem = args[i];
1562 CHECK_STRING (tem);
1563 if (STRING_MULTIBYTE (tem))
1564 tem = (code_convert_string_norecord
1565 (tem, XPROCESS (proc)->encode_coding_system, 1));
1566 new_argv[i - 2] = SDATA (tem);
1568 new_argv[i - 2] = 0;
1569 #endif /* not VMS */
1571 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1572 XPROCESS (proc)->decoding_carryover = make_number (0);
1573 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1574 XPROCESS (proc)->encoding_carryover = make_number (0);
1576 XPROCESS (proc)->inherit_coding_system_flag
1577 = (NILP (buffer) || !inherit_process_coding_system
1578 ? Qnil : Qt);
1580 create_process (proc, (char **) new_argv, current_dir);
1582 return unbind_to (count, proc);
1585 /* This function is the unwind_protect form for Fstart_process. If
1586 PROC doesn't have its pid set, then we know someone has signaled
1587 an error and the process wasn't started successfully, so we should
1588 remove it from the process list. */
1589 static Lisp_Object
1590 start_process_unwind (proc)
1591 Lisp_Object proc;
1593 if (!PROCESSP (proc))
1594 abort ();
1596 /* Was PROC started successfully? */
1597 if (XINT (XPROCESS (proc)->pid) <= 0)
1598 remove_process (proc);
1600 return Qnil;
1603 void
1604 create_process_1 (timer)
1605 struct atimer *timer;
1607 /* Nothing to do. */
1611 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1612 #ifdef USG
1613 #ifdef SIGCHLD
1614 /* Mimic blocking of signals on system V, which doesn't really have it. */
1616 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1617 int sigchld_deferred;
1619 SIGTYPE
1620 create_process_sigchld ()
1622 signal (SIGCHLD, create_process_sigchld);
1624 sigchld_deferred = 1;
1626 #endif
1627 #endif
1628 #endif
1630 #ifndef VMS /* VMS version of this function is in vmsproc.c. */
1631 void
1632 create_process (process, new_argv, current_dir)
1633 Lisp_Object process;
1634 char **new_argv;
1635 Lisp_Object current_dir;
1637 int pid, inchannel, outchannel;
1638 int sv[2];
1639 #ifdef POSIX_SIGNALS
1640 sigset_t procmask;
1641 sigset_t blocked;
1642 struct sigaction sigint_action;
1643 struct sigaction sigquit_action;
1644 #ifdef AIX
1645 struct sigaction sighup_action;
1646 #endif
1647 #else /* !POSIX_SIGNALS */
1648 #if 0
1649 #ifdef SIGCHLD
1650 SIGTYPE (*sigchld)();
1651 #endif
1652 #endif /* 0 */
1653 #endif /* !POSIX_SIGNALS */
1654 /* Use volatile to protect variables from being clobbered by longjmp. */
1655 volatile int forkin, forkout;
1656 volatile int pty_flag = 0;
1657 #ifndef USE_CRT_DLL
1658 extern char **environ;
1659 #endif
1661 inchannel = outchannel = -1;
1663 #ifdef HAVE_PTYS
1664 if (!NILP (Vprocess_connection_type))
1665 outchannel = inchannel = allocate_pty ();
1667 if (inchannel >= 0)
1669 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1670 /* On most USG systems it does not work to open the pty's tty here,
1671 then close it and reopen it in the child. */
1672 #ifdef O_NOCTTY
1673 /* Don't let this terminal become our controlling terminal
1674 (in case we don't have one). */
1675 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1676 #else
1677 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1678 #endif
1679 if (forkin < 0)
1680 report_file_error ("Opening pty", Qnil);
1681 #else
1682 forkin = forkout = -1;
1683 #endif /* not USG, or USG_SUBTTY_WORKS */
1684 pty_flag = 1;
1686 else
1687 #endif /* HAVE_PTYS */
1688 #ifdef SKTPAIR
1690 if (socketpair (AF_UNIX, SOCK_STREAM, 0, sv) < 0)
1691 report_file_error ("Opening socketpair", Qnil);
1692 outchannel = inchannel = sv[0];
1693 forkout = forkin = sv[1];
1695 #else /* not SKTPAIR */
1697 int tem;
1698 tem = pipe (sv);
1699 if (tem < 0)
1700 report_file_error ("Creating pipe", Qnil);
1701 inchannel = sv[0];
1702 forkout = sv[1];
1703 tem = pipe (sv);
1704 if (tem < 0)
1706 emacs_close (inchannel);
1707 emacs_close (forkout);
1708 report_file_error ("Creating pipe", Qnil);
1710 outchannel = sv[1];
1711 forkin = sv[0];
1713 #endif /* not SKTPAIR */
1715 #if 0
1716 /* Replaced by close_process_descs */
1717 set_exclusive_use (inchannel);
1718 set_exclusive_use (outchannel);
1719 #endif
1721 /* Stride people say it's a mystery why this is needed
1722 as well as the O_NDELAY, but that it fails without this. */
1723 #if defined (STRIDE) || (defined (pfa) && defined (HAVE_PTYS))
1725 int one = 1;
1726 ioctl (inchannel, FIONBIO, &one);
1728 #endif
1730 #ifdef O_NONBLOCK
1731 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1732 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1733 #else
1734 #ifdef O_NDELAY
1735 fcntl (inchannel, F_SETFL, O_NDELAY);
1736 fcntl (outchannel, F_SETFL, O_NDELAY);
1737 #endif
1738 #endif
1740 /* Record this as an active process, with its channels.
1741 As a result, child_setup will close Emacs's side of the pipes. */
1742 chan_process[inchannel] = process;
1743 XSETINT (XPROCESS (process)->infd, inchannel);
1744 XSETINT (XPROCESS (process)->outfd, outchannel);
1745 /* Record the tty descriptor used in the subprocess. */
1746 if (forkin < 0)
1747 XPROCESS (process)->subtty = Qnil;
1748 else
1749 XSETFASTINT (XPROCESS (process)->subtty, forkin);
1750 XPROCESS (process)->pty_flag = (pty_flag ? Qt : Qnil);
1751 XPROCESS (process)->status = Qrun;
1752 if (!proc_decode_coding_system[inchannel])
1753 proc_decode_coding_system[inchannel]
1754 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
1755 setup_coding_system (XPROCESS (process)->decode_coding_system,
1756 proc_decode_coding_system[inchannel]);
1757 if (!proc_encode_coding_system[outchannel])
1758 proc_encode_coding_system[outchannel]
1759 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
1760 setup_coding_system (XPROCESS (process)->encode_coding_system,
1761 proc_encode_coding_system[outchannel]);
1763 /* Delay interrupts until we have a chance to store
1764 the new fork's pid in its process structure */
1765 #ifdef POSIX_SIGNALS
1766 sigemptyset (&blocked);
1767 #ifdef SIGCHLD
1768 sigaddset (&blocked, SIGCHLD);
1769 #endif
1770 #ifdef HAVE_WORKING_VFORK
1771 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1772 this sets the parent's signal handlers as well as the child's.
1773 So delay all interrupts whose handlers the child might munge,
1774 and record the current handlers so they can be restored later. */
1775 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1776 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1777 #ifdef AIX
1778 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1779 #endif
1780 #endif /* HAVE_WORKING_VFORK */
1781 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1782 #else /* !POSIX_SIGNALS */
1783 #ifdef SIGCHLD
1784 #ifdef BSD4_1
1785 sighold (SIGCHLD);
1786 #else /* not BSD4_1 */
1787 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1788 sigsetmask (sigmask (SIGCHLD));
1789 #else /* ordinary USG */
1790 #if 0
1791 sigchld_deferred = 0;
1792 sigchld = signal (SIGCHLD, create_process_sigchld);
1793 #endif
1794 #endif /* ordinary USG */
1795 #endif /* not BSD4_1 */
1796 #endif /* SIGCHLD */
1797 #endif /* !POSIX_SIGNALS */
1799 FD_SET (inchannel, &input_wait_mask);
1800 FD_SET (inchannel, &non_keyboard_wait_mask);
1801 if (inchannel > max_process_desc)
1802 max_process_desc = inchannel;
1804 /* Until we store the proper pid, enable sigchld_handler
1805 to recognize an unknown pid as standing for this process.
1806 It is very important not to let this `marker' value stay
1807 in the table after this function has returned; if it does
1808 it might cause call-process to hang and subsequent asynchronous
1809 processes to get their return values scrambled. */
1810 XSETINT (XPROCESS (process)->pid, -1);
1812 BLOCK_INPUT;
1815 /* child_setup must clobber environ on systems with true vfork.
1816 Protect it from permanent change. */
1817 char **save_environ = environ;
1819 current_dir = ENCODE_FILE (current_dir);
1821 #ifndef WINDOWSNT
1822 pid = vfork ();
1823 if (pid == 0)
1824 #endif /* not WINDOWSNT */
1826 int xforkin = forkin;
1827 int xforkout = forkout;
1829 #if 0 /* This was probably a mistake--it duplicates code later on,
1830 but fails to handle all the cases. */
1831 /* Make sure SIGCHLD is not blocked in the child. */
1832 sigsetmask (SIGEMPTYMASK);
1833 #endif
1835 /* Make the pty be the controlling terminal of the process. */
1836 #ifdef HAVE_PTYS
1837 /* First, disconnect its current controlling terminal. */
1838 #ifdef HAVE_SETSID
1839 /* We tried doing setsid only if pty_flag, but it caused
1840 process_set_signal to fail on SGI when using a pipe. */
1841 setsid ();
1842 /* Make the pty's terminal the controlling terminal. */
1843 if (pty_flag)
1845 #ifdef TIOCSCTTY
1846 /* We ignore the return value
1847 because faith@cs.unc.edu says that is necessary on Linux. */
1848 ioctl (xforkin, TIOCSCTTY, 0);
1849 #endif
1851 #else /* not HAVE_SETSID */
1852 #ifdef USG
1853 /* It's very important to call setpgrp here and no time
1854 afterwards. Otherwise, we lose our controlling tty which
1855 is set when we open the pty. */
1856 setpgrp ();
1857 #endif /* USG */
1858 #endif /* not HAVE_SETSID */
1859 #if defined (HAVE_TERMIOS) && defined (LDISC1)
1860 if (pty_flag && xforkin >= 0)
1862 struct termios t;
1863 tcgetattr (xforkin, &t);
1864 t.c_lflag = LDISC1;
1865 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
1866 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
1868 #else
1869 #if defined (NTTYDISC) && defined (TIOCSETD)
1870 if (pty_flag && xforkin >= 0)
1872 /* Use new line discipline. */
1873 int ldisc = NTTYDISC;
1874 ioctl (xforkin, TIOCSETD, &ldisc);
1876 #endif
1877 #endif
1878 #ifdef TIOCNOTTY
1879 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
1880 can do TIOCSPGRP only to the process's controlling tty. */
1881 if (pty_flag)
1883 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
1884 I can't test it since I don't have 4.3. */
1885 int j = emacs_open ("/dev/tty", O_RDWR, 0);
1886 ioctl (j, TIOCNOTTY, 0);
1887 emacs_close (j);
1888 #ifndef USG
1889 /* In order to get a controlling terminal on some versions
1890 of BSD, it is necessary to put the process in pgrp 0
1891 before it opens the terminal. */
1892 #ifdef HAVE_SETPGID
1893 setpgid (0, 0);
1894 #else
1895 setpgrp (0, 0);
1896 #endif
1897 #endif
1899 #endif /* TIOCNOTTY */
1901 #if !defined (RTU) && !defined (UNIPLUS) && !defined (DONT_REOPEN_PTY)
1902 /*** There is a suggestion that this ought to be a
1903 conditional on TIOCSPGRP,
1904 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
1905 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
1906 that system does seem to need this code, even though
1907 both HAVE_SETSID and TIOCSCTTY are defined. */
1908 /* Now close the pty (if we had it open) and reopen it.
1909 This makes the pty the controlling terminal of the subprocess. */
1910 if (pty_flag)
1912 #ifdef SET_CHILD_PTY_PGRP
1913 int pgrp = getpid ();
1914 #endif
1916 /* I wonder if emacs_close (emacs_open (pty_name, ...))
1917 would work? */
1918 if (xforkin >= 0)
1919 emacs_close (xforkin);
1920 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
1922 if (xforkin < 0)
1924 emacs_write (1, "Couldn't open the pty terminal ", 31);
1925 emacs_write (1, pty_name, strlen (pty_name));
1926 emacs_write (1, "\n", 1);
1927 _exit (1);
1930 #ifdef SET_CHILD_PTY_PGRP
1931 ioctl (xforkin, TIOCSPGRP, &pgrp);
1932 ioctl (xforkout, TIOCSPGRP, &pgrp);
1933 #endif
1935 #endif /* not UNIPLUS and not RTU and not DONT_REOPEN_PTY */
1937 #ifdef SETUP_SLAVE_PTY
1938 if (pty_flag)
1940 SETUP_SLAVE_PTY;
1942 #endif /* SETUP_SLAVE_PTY */
1943 #ifdef AIX
1944 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
1945 Now reenable it in the child, so it will die when we want it to. */
1946 if (pty_flag)
1947 signal (SIGHUP, SIG_DFL);
1948 #endif
1949 #endif /* HAVE_PTYS */
1951 signal (SIGINT, SIG_DFL);
1952 signal (SIGQUIT, SIG_DFL);
1954 /* Stop blocking signals in the child. */
1955 #ifdef POSIX_SIGNALS
1956 sigprocmask (SIG_SETMASK, &procmask, 0);
1957 #else /* !POSIX_SIGNALS */
1958 #ifdef SIGCHLD
1959 #ifdef BSD4_1
1960 sigrelse (SIGCHLD);
1961 #else /* not BSD4_1 */
1962 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
1963 sigsetmask (SIGEMPTYMASK);
1964 #else /* ordinary USG */
1965 #if 0
1966 signal (SIGCHLD, sigchld);
1967 #endif
1968 #endif /* ordinary USG */
1969 #endif /* not BSD4_1 */
1970 #endif /* SIGCHLD */
1971 #endif /* !POSIX_SIGNALS */
1973 if (pty_flag)
1974 child_setup_tty (xforkout);
1975 #ifdef WINDOWSNT
1976 pid = child_setup (xforkin, xforkout, xforkout,
1977 new_argv, 1, current_dir);
1978 #else /* not WINDOWSNT */
1979 child_setup (xforkin, xforkout, xforkout,
1980 new_argv, 1, current_dir);
1981 #endif /* not WINDOWSNT */
1983 environ = save_environ;
1986 UNBLOCK_INPUT;
1988 /* This runs in the Emacs process. */
1989 if (pid < 0)
1991 if (forkin >= 0)
1992 emacs_close (forkin);
1993 if (forkin != forkout && forkout >= 0)
1994 emacs_close (forkout);
1996 else
1998 /* vfork succeeded. */
1999 XSETFASTINT (XPROCESS (process)->pid, pid);
2001 #ifdef WINDOWSNT
2002 register_child (pid, inchannel);
2003 #endif /* WINDOWSNT */
2005 /* If the subfork execv fails, and it exits,
2006 this close hangs. I don't know why.
2007 So have an interrupt jar it loose. */
2009 struct atimer *timer;
2010 EMACS_TIME offset;
2012 stop_polling ();
2013 EMACS_SET_SECS_USECS (offset, 1, 0);
2014 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2016 XPROCESS (process)->subtty = Qnil;
2017 if (forkin >= 0)
2018 emacs_close (forkin);
2020 cancel_atimer (timer);
2021 start_polling ();
2024 if (forkin != forkout && forkout >= 0)
2025 emacs_close (forkout);
2027 #ifdef HAVE_PTYS
2028 if (pty_flag)
2029 XPROCESS (process)->tty_name = build_string (pty_name);
2030 else
2031 #endif
2032 XPROCESS (process)->tty_name = Qnil;
2035 /* Restore the signal state whether vfork succeeded or not.
2036 (We will signal an error, below, if it failed.) */
2037 #ifdef POSIX_SIGNALS
2038 #ifdef HAVE_WORKING_VFORK
2039 /* Restore the parent's signal handlers. */
2040 sigaction (SIGINT, &sigint_action, 0);
2041 sigaction (SIGQUIT, &sigquit_action, 0);
2042 #ifdef AIX
2043 sigaction (SIGHUP, &sighup_action, 0);
2044 #endif
2045 #endif /* HAVE_WORKING_VFORK */
2046 /* Stop blocking signals in the parent. */
2047 sigprocmask (SIG_SETMASK, &procmask, 0);
2048 #else /* !POSIX_SIGNALS */
2049 #ifdef SIGCHLD
2050 #ifdef BSD4_1
2051 sigrelse (SIGCHLD);
2052 #else /* not BSD4_1 */
2053 #if defined (BSD_SYSTEM) || defined (UNIPLUS) || defined (HPUX)
2054 sigsetmask (SIGEMPTYMASK);
2055 #else /* ordinary USG */
2056 #if 0
2057 signal (SIGCHLD, sigchld);
2058 /* Now really handle any of these signals
2059 that came in during this function. */
2060 if (sigchld_deferred)
2061 kill (getpid (), SIGCHLD);
2062 #endif
2063 #endif /* ordinary USG */
2064 #endif /* not BSD4_1 */
2065 #endif /* SIGCHLD */
2066 #endif /* !POSIX_SIGNALS */
2068 /* Now generate the error if vfork failed. */
2069 if (pid < 0)
2070 report_file_error ("Doing vfork", Qnil);
2072 #endif /* not VMS */
2075 #ifdef HAVE_SOCKETS
2077 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2078 The address family of sa is not included in the result. */
2080 static Lisp_Object
2081 conv_sockaddr_to_lisp (sa, len)
2082 struct sockaddr *sa;
2083 int len;
2085 Lisp_Object address;
2086 int i;
2087 unsigned char *cp;
2088 register struct Lisp_Vector *p;
2090 switch (sa->sa_family)
2092 case AF_INET:
2094 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2095 len = sizeof (sin->sin_addr) + 1;
2096 address = Fmake_vector (make_number (len), Qnil);
2097 p = XVECTOR (address);
2098 p->contents[--len] = make_number (ntohs (sin->sin_port));
2099 cp = (unsigned char *)&sin->sin_addr;
2100 break;
2102 #ifdef HAVE_LOCAL_SOCKETS
2103 case AF_LOCAL:
2105 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2106 for (i = 0; i < sizeof (sockun->sun_path); i++)
2107 if (sockun->sun_path[i] == 0)
2108 break;
2109 return make_unibyte_string (sockun->sun_path, i);
2111 #endif
2112 default:
2113 len -= sizeof (sa->sa_family);
2114 address = Fcons (make_number (sa->sa_family),
2115 Fmake_vector (make_number (len), Qnil));
2116 p = XVECTOR (XCDR (address));
2117 cp = (unsigned char *) sa + sizeof (sa->sa_family);
2118 break;
2121 i = 0;
2122 while (i < len)
2123 p->contents[i++] = make_number (*cp++);
2125 return address;
2129 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2131 static int
2132 get_lisp_to_sockaddr_size (address, familyp)
2133 Lisp_Object address;
2134 int *familyp;
2136 register struct Lisp_Vector *p;
2138 if (VECTORP (address))
2140 p = XVECTOR (address);
2141 if (p->size == 5)
2143 *familyp = AF_INET;
2144 return sizeof (struct sockaddr_in);
2147 #ifdef HAVE_LOCAL_SOCKETS
2148 else if (STRINGP (address))
2150 *familyp = AF_LOCAL;
2151 return sizeof (struct sockaddr_un);
2153 #endif
2154 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2156 struct sockaddr *sa;
2157 *familyp = XINT (XCAR (address));
2158 p = XVECTOR (XCDR (address));
2159 return p->size + sizeof (sa->sa_family);
2161 return 0;
2164 /* Convert an address object (vector or string) to an internal sockaddr.
2165 Format of address has already been validated by size_lisp_to_sockaddr. */
2167 static void
2168 conv_lisp_to_sockaddr (family, address, sa, len)
2169 int family;
2170 Lisp_Object address;
2171 struct sockaddr *sa;
2172 int len;
2174 register struct Lisp_Vector *p;
2175 register unsigned char *cp;
2176 register int i;
2178 bzero (sa, len);
2179 sa->sa_family = family;
2181 if (VECTORP (address))
2183 p = XVECTOR (address);
2184 if (family == AF_INET)
2186 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2187 len = sizeof (sin->sin_addr) + 1;
2188 i = XINT (p->contents[--len]);
2189 sin->sin_port = htons (i);
2190 cp = (unsigned char *)&sin->sin_addr;
2193 else if (STRINGP (address))
2195 #ifdef HAVE_LOCAL_SOCKETS
2196 if (family == AF_LOCAL)
2198 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2199 cp = SDATA (address);
2200 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2201 sockun->sun_path[i] = *cp++;
2203 #endif
2204 return;
2206 else
2208 p = XVECTOR (XCDR (address));
2209 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2212 for (i = 0; i < len; i++)
2213 if (INTEGERP (p->contents[i]))
2214 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2217 #ifdef DATAGRAM_SOCKETS
2218 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2219 1, 1, 0,
2220 doc: /* Get the current datagram address associated with PROCESS. */)
2221 (process)
2222 Lisp_Object process;
2224 int channel;
2226 CHECK_PROCESS (process);
2228 if (!DATAGRAM_CONN_P (process))
2229 return Qnil;
2231 channel = XINT (XPROCESS (process)->infd);
2232 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2233 datagram_address[channel].len);
2236 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2237 2, 2, 0,
2238 doc: /* Set the datagram address for PROCESS to ADDRESS.
2239 Returns nil upon error setting address, ADDRESS otherwise. */)
2240 (process, address)
2241 Lisp_Object process, address;
2243 int channel;
2244 int family, len;
2246 CHECK_PROCESS (process);
2248 if (!DATAGRAM_CONN_P (process))
2249 return Qnil;
2251 channel = XINT (XPROCESS (process)->infd);
2253 len = get_lisp_to_sockaddr_size (address, &family);
2254 if (datagram_address[channel].len != len)
2255 return Qnil;
2256 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2257 return address;
2259 #endif
2262 static struct socket_options {
2263 /* The name of this option. Should be lowercase version of option
2264 name without SO_ prefix. */
2265 char *name;
2266 /* Length of name. */
2267 int nlen;
2268 /* Option level SOL_... */
2269 int optlevel;
2270 /* Option number SO_... */
2271 int optnum;
2272 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_STR, SOPT_LINGER } opttype;
2273 } socket_options[] =
2275 #ifdef SO_BINDTODEVICE
2276 { "bindtodevice", 12, SOL_SOCKET, SO_BINDTODEVICE, SOPT_STR },
2277 #endif
2278 #ifdef SO_BROADCAST
2279 { "broadcast", 9, SOL_SOCKET, SO_BROADCAST, SOPT_BOOL },
2280 #endif
2281 #ifdef SO_DONTROUTE
2282 { "dontroute", 9, SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL },
2283 #endif
2284 #ifdef SO_KEEPALIVE
2285 { "keepalive", 9, SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL },
2286 #endif
2287 #ifdef SO_LINGER
2288 { "linger", 6, SOL_SOCKET, SO_LINGER, SOPT_LINGER },
2289 #endif
2290 #ifdef SO_OOBINLINE
2291 { "oobinline", 9, SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL },
2292 #endif
2293 #ifdef SO_PRIORITY
2294 { "priority", 8, SOL_SOCKET, SO_PRIORITY, SOPT_INT },
2295 #endif
2296 #ifdef SO_REUSEADDR
2297 { "reuseaddr", 9, SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL },
2298 #endif
2299 { 0, 0, 0, 0, SOPT_UNKNOWN }
2302 /* Process list of socket options OPTS on socket S.
2303 Only check if options are supported is S < 0.
2304 If NO_ERROR is non-zero, continue silently if an option
2305 cannot be set.
2307 Each element specifies one option. An element is either a string
2308 "OPTION=VALUE" or a cons (OPTION . VALUE) where OPTION is a string
2309 or a symbol. */
2311 static int
2312 set_socket_options (s, opts, no_error)
2313 int s;
2314 Lisp_Object opts;
2315 int no_error;
2317 if (!CONSP (opts))
2318 opts = Fcons (opts, Qnil);
2320 while (CONSP (opts))
2322 Lisp_Object opt;
2323 Lisp_Object val;
2324 char *name, *arg;
2325 struct socket_options *sopt;
2326 int ret = 0;
2328 opt = XCAR (opts);
2329 opts = XCDR (opts);
2331 name = 0;
2332 val = Qt;
2333 if (CONSP (opt))
2335 val = XCDR (opt);
2336 opt = XCAR (opt);
2338 if (STRINGP (opt))
2339 name = (char *) SDATA (opt);
2340 else if (SYMBOLP (opt))
2341 name = (char *) SDATA (SYMBOL_NAME (opt));
2342 else {
2343 error ("Mal-formed option list");
2344 return 0;
2347 if (strncmp (name, "no", 2) == 0)
2349 val = Qnil;
2350 name += 2;
2353 arg = 0;
2354 for (sopt = socket_options; sopt->name; sopt++)
2355 if (strncmp (name, sopt->name, sopt->nlen) == 0)
2357 if (name[sopt->nlen] == 0)
2358 break;
2359 if (name[sopt->nlen] == '=')
2361 arg = name + sopt->nlen + 1;
2362 break;
2366 switch (sopt->opttype)
2368 case SOPT_BOOL:
2370 int optval;
2371 if (s < 0)
2372 return 1;
2373 if (arg)
2374 optval = (*arg == '0' || *arg == 'n') ? 0 : 1;
2375 else if (INTEGERP (val))
2376 optval = XINT (val) == 0 ? 0 : 1;
2377 else
2378 optval = NILP (val) ? 0 : 1;
2379 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2380 &optval, sizeof (optval));
2381 break;
2384 case SOPT_INT:
2386 int optval;
2387 if (arg)
2388 optval = atoi(arg);
2389 else if (INTEGERP (val))
2390 optval = XINT (val);
2391 else
2392 error ("Bad option argument for %s", name);
2393 if (s < 0)
2394 return 1;
2395 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2396 &optval, sizeof (optval));
2397 break;
2400 case SOPT_STR:
2402 if (!arg)
2404 if (NILP (val))
2405 arg = "";
2406 else if (STRINGP (val))
2407 arg = (char *) SDATA (val);
2408 else if (XSYMBOL (val))
2409 arg = (char *) SDATA (SYMBOL_NAME (val));
2410 else
2411 error ("Invalid argument to %s option", name);
2413 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2414 arg, strlen (arg));
2417 #ifdef SO_LINGER
2418 case SOPT_LINGER:
2420 struct linger linger;
2422 linger.l_onoff = 1;
2423 linger.l_linger = 0;
2425 if (s < 0)
2426 return 1;
2428 if (arg)
2430 if (*arg == 'n' || *arg == 't' || *arg == 'y')
2431 linger.l_onoff = (*arg == 'n') ? 0 : 1;
2432 else
2433 linger.l_linger = atoi(arg);
2435 else if (INTEGERP (val))
2436 linger.l_linger = XINT (val);
2437 else
2438 linger.l_onoff = NILP (val) ? 0 : 1;
2439 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2440 &linger, sizeof (linger));
2441 break;
2443 #endif
2444 default:
2445 if (s < 0)
2446 return 0;
2447 if (no_error)
2448 continue;
2449 error ("Unsupported option: %s", name);
2451 if (ret < 0 && ! no_error)
2452 report_file_error ("Cannot set network option: %s", opt);
2454 return 1;
2457 DEFUN ("set-network-process-options",
2458 Fset_network_process_options, Sset_network_process_options,
2459 1, MANY, 0,
2460 doc: /* Set one or more options for network process PROCESS.
2461 Each option is either a string "OPT=VALUE" or a cons (OPT . VALUE).
2462 A boolean value is false if it either zero or nil, true otherwise.
2464 The following options are known. Consult the relevant system manual
2465 pages for more information.
2467 bindtodevice=NAME -- bind to interface NAME, or remove binding if nil.
2468 broadcast=BOOL -- Allow send and receive of datagram broadcasts.
2469 dontroute=BOOL -- Only send to directly connected hosts.
2470 keepalive=BOOL -- Send keep-alive messages on network stream.
2471 linger=BOOL or TIMEOUT -- Send queued messages before closing.
2472 oobinline=BOOL -- Place out-of-band data in receive data stream.
2473 priority=INT -- Set protocol defined priority for sent packets.
2474 reuseaddr=BOOL -- Allow reusing a recently used address.
2476 usage: (set-network-process-options PROCESS &rest OPTIONS) */)
2477 (nargs, args)
2478 int nargs;
2479 Lisp_Object *args;
2481 Lisp_Object process;
2482 Lisp_Object opts;
2484 process = args[0];
2485 CHECK_PROCESS (process);
2486 if (nargs > 1 && XINT (XPROCESS (process)->infd) >= 0)
2488 opts = Flist (nargs, args);
2489 set_socket_options (XINT (XPROCESS (process)->infd), opts, 0);
2491 return process;
2494 /* A version of request_sigio suitable for a record_unwind_protect. */
2496 Lisp_Object
2497 unwind_request_sigio (dummy)
2498 Lisp_Object dummy;
2500 if (interrupt_input)
2501 request_sigio ();
2502 return Qnil;
2505 /* Create a network stream/datagram client/server process. Treated
2506 exactly like a normal process when reading and writing. Primary
2507 differences are in status display and process deletion. A network
2508 connection has no PID; you cannot signal it. All you can do is
2509 stop/continue it and deactivate/close it via delete-process */
2511 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2512 0, MANY, 0,
2513 doc: /* Create and return a network server or client process.
2515 In Emacs, network connections are represented by process objects, so
2516 input and output work as for subprocesses and `delete-process' closes
2517 a network connection. However, a network process has no process id,
2518 it cannot be signalled, and the status codes are different from normal
2519 processes.
2521 Arguments are specified as keyword/argument pairs. The following
2522 arguments are defined:
2524 :name NAME -- NAME is name for process. It is modified if necessary
2525 to make it unique.
2527 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2528 with the process. Process output goes at end of that buffer, unless
2529 you specify an output stream or filter function to handle the output.
2530 BUFFER may be also nil, meaning that this process is not associated
2531 with any buffer.
2533 :host HOST -- HOST is name of the host to connect to, or its IP
2534 address. The symbol `local' specifies the local host. If specified
2535 for a server process, it must be a valid name or address for the local
2536 host, and only clients connecting to that address will be accepted.
2538 :service SERVICE -- SERVICE is name of the service desired, or an
2539 integer specifying a port number to connect to. If SERVICE is t,
2540 a random port number is selected for the server.
2542 :type TYPE -- TYPE is the type of connection. The default (nil) is a
2543 stream type connection, `datagram' creates a datagram type connection.
2545 :family FAMILY -- FAMILY is the address (and protocol) family for the
2546 service specified by HOST and SERVICE. The default address family is
2547 Inet (or IPv4) for the host and port number specified by HOST and
2548 SERVICE. Other address families supported are:
2549 local -- for a local (i.e. UNIX) address specified by SERVICE.
2551 :local ADDRESS -- ADDRESS is the local address used for the connection.
2552 This parameter is ignored when opening a client process. When specified
2553 for a server process, the FAMILY, HOST and SERVICE args are ignored.
2555 :remote ADDRESS -- ADDRESS is the remote partner's address for the
2556 connection. This parameter is ignored when opening a stream server
2557 process. For a datagram server process, it specifies the initial
2558 setting of the remote datagram address. When specified for a client
2559 process, the FAMILY, HOST, and SERVICE args are ignored.
2561 The format of ADDRESS depends on the address family:
2562 - An IPv4 address is represented as an vector of integers [A B C D P]
2563 corresponding to numeric IP address A.B.C.D and port number P.
2564 - A local address is represented as a string with the address in the
2565 local address space.
2566 - An "unsupported family" address is represented by a cons (F . AV)
2567 where F is the family number and AV is a vector containing the socket
2568 address data with one element per address data byte. Do not rely on
2569 this format in portable code, as it may depend on implementation
2570 defined constants, data sizes, and data structure alignment.
2572 :coding CODING -- CODING is coding system for this process.
2574 :options OPTIONS -- Set the specified options for the network process.
2575 See `set-network-process-options' for details.
2577 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
2578 return without waiting for the connection to complete; instead, the
2579 sentinel function will be called with second arg matching "open" (if
2580 successful) or "failed" when the connect completes. Default is to use
2581 a blocking connect (i.e. wait) for stream type connections.
2583 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
2584 running when emacs is exited.
2586 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
2587 In the stopped state, a server process does not accept new
2588 connections, and a client process does not handle incoming traffic.
2589 The stopped state is cleared by `continue-process' and set by
2590 `stop-process'.
2592 :filter FILTER -- Install FILTER as the process filter.
2594 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2596 :log LOG -- Install LOG as the server process log function. This
2597 function is called when the server accepts a network connection from a
2598 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
2599 is the server process, CLIENT is the new process for the connection,
2600 and MESSAGE is a string.
2602 :vars VARS -- Initialize the process' private variables according to
2603 a list of variable/value pairs (VAR1 VAL1 VAR2 VAL2...).
2605 :server BOOL -- if BOOL is non-nil, create a server process for the
2606 specified FAMILY, SERVICE, and connection type (stream or datagram).
2607 Default is a client process.
2609 A server process will listen for and accept connections from
2610 clients. When a client connection is accepted, a new network process
2611 is created for the connection with the following parameters:
2612 - The client's process name is constructed by concatenating the server
2613 process' NAME and a client identification string.
2614 - If the FILTER argument is non-nil, the client process will not get a
2615 separate process buffer; otherwise, the client's process buffer is a newly
2616 created buffer named after the server process' BUFFER name or process
2617 NAME concatenated with the client identification string.
2618 - The connection type and the process filter and sentinel parameters are
2619 inherited from the server process' TYPE, FILTER and SENTINEL.
2620 - The client process' contact info is set according to the client's
2621 addressing information (typically an IP address and a port number).
2622 - The client process' private variables are initialized from the
2623 server's private variables.
2625 Notice that the FILTER and SENTINEL args are never used directly by
2626 the server process. Also, the BUFFER argument is not used directly by
2627 the server process, but via the optional :log function, accepted (and
2628 failed) connections may be logged in the server process' buffer.
2630 The original argument list, modified with the actual connection
2631 information, is available via the `process-contact' function.
2633 usage: (make-network-process &rest ARGS) */)
2634 (nargs, args)
2635 int nargs;
2636 Lisp_Object *args;
2638 Lisp_Object proc;
2639 Lisp_Object contact;
2640 struct Lisp_Process *p;
2641 #ifdef HAVE_GETADDRINFO
2642 struct addrinfo ai, *res, *lres;
2643 struct addrinfo hints;
2644 char *portstring, portbuf[128];
2645 #else /* HAVE_GETADDRINFO */
2646 struct _emacs_addrinfo
2648 int ai_family;
2649 int ai_socktype;
2650 int ai_protocol;
2651 int ai_addrlen;
2652 struct sockaddr *ai_addr;
2653 struct _emacs_addrinfo *ai_next;
2654 } ai, *res, *lres;
2655 #endif /* HAVE_GETADDRINFO */
2656 struct sockaddr_in address_in;
2657 #ifdef HAVE_LOCAL_SOCKETS
2658 struct sockaddr_un address_un;
2659 #endif
2660 int port;
2661 int ret = 0;
2662 int xerrno = 0;
2663 int s = -1, outch, inch;
2664 struct gcpro gcpro1;
2665 int retry = 0;
2666 int count = SPECPDL_INDEX ();
2667 int count1;
2668 Lisp_Object QCaddress; /* one of QClocal or QCremote */
2669 Lisp_Object tem;
2670 Lisp_Object name, buffer, host, service, address;
2671 Lisp_Object filter, sentinel;
2672 int is_non_blocking_client = 0;
2673 int is_server = 0;
2674 int socktype;
2675 int family = -1;
2677 if (nargs == 0)
2678 return Qnil;
2680 /* Save arguments for process-contact and clone-process. */
2681 contact = Flist (nargs, args);
2682 GCPRO1 (contact);
2684 #ifdef WINDOWSNT
2685 /* Ensure socket support is loaded if available. */
2686 init_winsock (TRUE);
2687 #endif
2689 /* :type TYPE (nil: stream, datagram */
2690 tem = Fplist_get (contact, QCtype);
2691 if (NILP (tem))
2692 socktype = SOCK_STREAM;
2693 #ifdef DATAGRAM_SOCKETS
2694 else if (EQ (tem, Qdatagram))
2695 socktype = SOCK_DGRAM;
2696 #endif
2697 else
2698 error ("Unsupported connection type");
2700 /* :server BOOL */
2701 tem = Fplist_get (contact, QCserver);
2702 if (!NILP (tem))
2704 /* Don't support network sockets when non-blocking mode is
2705 not available, since a blocked Emacs is not useful. */
2706 #if defined(TERM) || (!defined(O_NONBLOCK) && !defined(O_NDELAY))
2707 error ("Network servers not supported");
2708 #else
2709 is_server = 1;
2710 #endif
2713 /* Make QCaddress an alias for :local (server) or :remote (client). */
2714 QCaddress = is_server ? QClocal : QCremote;
2716 /* :wait BOOL */
2717 if (!is_server && socktype == SOCK_STREAM
2718 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
2720 #ifndef NON_BLOCKING_CONNECT
2721 error ("Non-blocking connect not supported");
2722 #else
2723 is_non_blocking_client = 1;
2724 #endif
2727 name = Fplist_get (contact, QCname);
2728 buffer = Fplist_get (contact, QCbuffer);
2729 filter = Fplist_get (contact, QCfilter);
2730 sentinel = Fplist_get (contact, QCsentinel);
2732 CHECK_STRING (name);
2734 #ifdef TERM
2735 /* Let's handle TERM before things get complicated ... */
2736 host = Fplist_get (contact, QChost);
2737 CHECK_STRING (host);
2739 service = Fplist_get (contact, QCservice);
2740 if (INTEGERP (service))
2741 port = htons ((unsigned short) XINT (service));
2742 else
2744 struct servent *svc_info;
2745 CHECK_STRING (service);
2746 svc_info = getservbyname (SDATA (service), "tcp");
2747 if (svc_info == 0)
2748 error ("Unknown service: %s", SDATA (service));
2749 port = svc_info->s_port;
2752 s = connect_server (0);
2753 if (s < 0)
2754 report_file_error ("error creating socket", Fcons (name, Qnil));
2755 send_command (s, C_PORT, 0, "%s:%d", SDATA (host), ntohs (port));
2756 send_command (s, C_DUMB, 1, 0);
2758 #else /* not TERM */
2760 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
2761 ai.ai_socktype = socktype;
2762 ai.ai_protocol = 0;
2763 ai.ai_next = NULL;
2764 res = &ai;
2766 /* :local ADDRESS or :remote ADDRESS */
2767 address = Fplist_get (contact, QCaddress);
2768 if (!NILP (address))
2770 host = service = Qnil;
2772 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
2773 error ("Malformed :address");
2774 ai.ai_family = family;
2775 ai.ai_addr = alloca (ai.ai_addrlen);
2776 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
2777 goto open_socket;
2780 /* :family FAMILY -- nil (for Inet), local, or integer. */
2781 tem = Fplist_get (contact, QCfamily);
2782 if (INTEGERP (tem))
2783 family = XINT (tem);
2784 else
2786 if (NILP (tem))
2787 family = AF_INET;
2788 #ifdef HAVE_LOCAL_SOCKETS
2789 else if (EQ (tem, Qlocal))
2790 family = AF_LOCAL;
2791 #endif
2793 if (family < 0)
2794 error ("Unknown address family");
2795 ai.ai_family = family;
2797 /* :service SERVICE -- string, integer (port number), or t (random port). */
2798 service = Fplist_get (contact, QCservice);
2800 #ifdef HAVE_LOCAL_SOCKETS
2801 if (family == AF_LOCAL)
2803 /* Host is not used. */
2804 host = Qnil;
2805 CHECK_STRING (service);
2806 bzero (&address_un, sizeof address_un);
2807 address_un.sun_family = AF_LOCAL;
2808 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
2809 ai.ai_addr = (struct sockaddr *) &address_un;
2810 ai.ai_addrlen = sizeof address_un;
2811 goto open_socket;
2813 #endif
2815 /* :host HOST -- hostname, ip address, or 'local for localhost. */
2816 host = Fplist_get (contact, QChost);
2817 if (!NILP (host))
2819 if (EQ (host, Qlocal))
2820 host = build_string ("localhost");
2821 CHECK_STRING (host);
2824 /* Slow down polling to every ten seconds.
2825 Some kernels have a bug which causes retrying connect to fail
2826 after a connect. Polling can interfere with gethostbyname too. */
2827 #ifdef POLL_FOR_INPUT
2828 if (socktype == SOCK_STREAM)
2830 record_unwind_protect (unwind_stop_other_atimers, Qnil);
2831 bind_polling_period (10);
2833 #endif
2835 #ifdef HAVE_GETADDRINFO
2836 /* If we have a host, use getaddrinfo to resolve both host and service.
2837 Otherwise, use getservbyname to lookup the service. */
2838 if (!NILP (host))
2841 /* SERVICE can either be a string or int.
2842 Convert to a C string for later use by getaddrinfo. */
2843 if (EQ (service, Qt))
2844 portstring = "0";
2845 else if (INTEGERP (service))
2847 sprintf (portbuf, "%ld", (long) XINT (service));
2848 portstring = portbuf;
2850 else
2852 CHECK_STRING (service);
2853 portstring = SDATA (service);
2856 immediate_quit = 1;
2857 QUIT;
2858 memset (&hints, 0, sizeof (hints));
2859 hints.ai_flags = 0;
2860 hints.ai_family = NILP (Fplist_member (contact, QCfamily)) ? AF_UNSPEC : family;
2861 hints.ai_socktype = socktype;
2862 hints.ai_protocol = 0;
2863 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
2864 if (ret)
2865 #ifdef HAVE_GAI_STRERROR
2866 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
2867 #else
2868 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
2869 #endif
2870 immediate_quit = 0;
2872 goto open_socket;
2874 #endif /* HAVE_GETADDRINFO */
2876 /* We end up here if getaddrinfo is not defined, or in case no hostname
2877 has been specified (e.g. for a local server process). */
2879 if (EQ (service, Qt))
2880 port = 0;
2881 else if (INTEGERP (service))
2882 port = htons ((unsigned short) XINT (service));
2883 else
2885 struct servent *svc_info;
2886 CHECK_STRING (service);
2887 svc_info = getservbyname (SDATA (service),
2888 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
2889 if (svc_info == 0)
2890 error ("Unknown service: %s", SDATA (service));
2891 port = svc_info->s_port;
2894 bzero (&address_in, sizeof address_in);
2895 address_in.sin_family = family;
2896 address_in.sin_addr.s_addr = INADDR_ANY;
2897 address_in.sin_port = port;
2899 #ifndef HAVE_GETADDRINFO
2900 if (!NILP (host))
2902 struct hostent *host_info_ptr;
2904 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
2905 as it may `hang' emacs for a very long time. */
2906 immediate_quit = 1;
2907 QUIT;
2908 host_info_ptr = gethostbyname (SDATA (host));
2909 immediate_quit = 0;
2911 if (host_info_ptr)
2913 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
2914 host_info_ptr->h_length);
2915 family = host_info_ptr->h_addrtype;
2916 address_in.sin_family = family;
2918 else
2919 /* Attempt to interpret host as numeric inet address */
2921 IN_ADDR numeric_addr;
2922 numeric_addr = inet_addr ((char *) SDATA (host));
2923 if (NUMERIC_ADDR_ERROR)
2924 error ("Unknown host \"%s\"", SDATA (host));
2926 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
2927 sizeof (address_in.sin_addr));
2931 #endif /* not HAVE_GETADDRINFO */
2933 ai.ai_family = family;
2934 ai.ai_addr = (struct sockaddr *) &address_in;
2935 ai.ai_addrlen = sizeof address_in;
2937 open_socket:
2939 /* Kernel bugs (on Ultrix at least) cause lossage (not just EINTR)
2940 when connect is interrupted. So let's not let it get interrupted.
2941 Note we do not turn off polling, because polling is only used
2942 when not interrupt_input, and thus not normally used on the systems
2943 which have this bug. On systems which use polling, there's no way
2944 to quit if polling is turned off. */
2945 if (interrupt_input
2946 && !is_server && socktype == SOCK_STREAM)
2948 /* Comment from KFS: The original open-network-stream code
2949 didn't unwind protect this, but it seems like the proper
2950 thing to do. In any case, I don't see how it could harm to
2951 do this -- and it makes cleanup (using unbind_to) easier. */
2952 record_unwind_protect (unwind_request_sigio, Qnil);
2953 unrequest_sigio ();
2956 /* Do this in case we never enter the for-loop below. */
2957 count1 = SPECPDL_INDEX ();
2958 s = -1;
2960 for (lres = res; lres; lres = lres->ai_next)
2962 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
2963 if (s < 0)
2965 xerrno = errno;
2966 continue;
2969 #ifdef DATAGRAM_SOCKETS
2970 if (!is_server && socktype == SOCK_DGRAM)
2971 break;
2972 #endif /* DATAGRAM_SOCKETS */
2974 #ifdef NON_BLOCKING_CONNECT
2975 if (is_non_blocking_client)
2977 #ifdef O_NONBLOCK
2978 ret = fcntl (s, F_SETFL, O_NONBLOCK);
2979 #else
2980 ret = fcntl (s, F_SETFL, O_NDELAY);
2981 #endif
2982 if (ret < 0)
2984 xerrno = errno;
2985 emacs_close (s);
2986 s = -1;
2987 continue;
2990 #endif
2992 /* Make us close S if quit. */
2993 record_unwind_protect (close_file_unwind, make_number (s));
2995 if (is_server)
2997 /* Configure as a server socket. */
2998 #ifdef HAVE_LOCAL_SOCKETS
2999 if (family != AF_LOCAL)
3000 #endif
3002 int optval = 1;
3003 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3004 report_file_error ("Cannot set reuse option on server socket.", Qnil);
3007 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3008 report_file_error ("Cannot bind server socket", Qnil);
3010 #ifdef HAVE_GETSOCKNAME
3011 if (EQ (service, Qt))
3013 struct sockaddr_in sa1;
3014 int len1 = sizeof (sa1);
3015 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3017 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3018 service = make_number (ntohs (sa1.sin_port));
3019 contact = Fplist_put (contact, QCservice, service);
3022 #endif
3024 if (socktype == SOCK_STREAM && listen (s, 5))
3025 report_file_error ("Cannot listen on server socket", Qnil);
3027 break;
3030 retry_connect:
3032 immediate_quit = 1;
3033 QUIT;
3035 /* This turns off all alarm-based interrupts; the
3036 bind_polling_period call above doesn't always turn all the
3037 short-interval ones off, especially if interrupt_input is
3038 set.
3040 It'd be nice to be able to control the connect timeout
3041 though. Would non-blocking connect calls be portable?
3043 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3045 turn_on_atimers (0);
3047 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3048 xerrno = errno;
3050 turn_on_atimers (1);
3052 if (ret == 0 || xerrno == EISCONN)
3054 /* The unwind-protect will be discarded afterwards.
3055 Likewise for immediate_quit. */
3056 break;
3059 #ifdef NON_BLOCKING_CONNECT
3060 #ifdef EINPROGRESS
3061 if (is_non_blocking_client && xerrno == EINPROGRESS)
3062 break;
3063 #else
3064 #ifdef EWOULDBLOCK
3065 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3066 break;
3067 #endif
3068 #endif
3069 #endif
3071 immediate_quit = 0;
3073 if (xerrno == EINTR)
3074 goto retry_connect;
3075 if (xerrno == EADDRINUSE && retry < 20)
3077 /* A delay here is needed on some FreeBSD systems,
3078 and it is harmless, since this retrying takes time anyway
3079 and should be infrequent. */
3080 Fsleep_for (make_number (1), Qnil);
3081 retry++;
3082 goto retry_connect;
3085 /* Discard the unwind protect closing S. */
3086 specpdl_ptr = specpdl + count1;
3087 emacs_close (s);
3088 s = -1;
3091 if (s >= 0)
3093 #ifdef DATAGRAM_SOCKETS
3094 if (socktype == SOCK_DGRAM)
3096 if (datagram_address[s].sa)
3097 abort ();
3098 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3099 datagram_address[s].len = lres->ai_addrlen;
3100 if (is_server)
3102 Lisp_Object remote;
3103 bzero (datagram_address[s].sa, lres->ai_addrlen);
3104 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3106 int rfamily, rlen;
3107 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3108 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3109 conv_lisp_to_sockaddr (rfamily, remote,
3110 datagram_address[s].sa, rlen);
3113 else
3114 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3116 #endif
3117 contact = Fplist_put (contact, QCaddress,
3118 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3119 #ifdef HAVE_GETSOCKNAME
3120 if (!is_server)
3122 struct sockaddr_in sa1;
3123 int len1 = sizeof (sa1);
3124 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3125 contact = Fplist_put (contact, QClocal,
3126 conv_sockaddr_to_lisp (&sa1, len1));
3128 #endif
3131 #ifdef HAVE_GETADDRINFO
3132 if (res != &ai)
3133 freeaddrinfo (res);
3134 #endif
3136 immediate_quit = 0;
3138 /* Discard the unwind protect for closing S, if any. */
3139 specpdl_ptr = specpdl + count1;
3141 /* Unwind bind_polling_period and request_sigio. */
3142 unbind_to (count, Qnil);
3144 if (s < 0)
3146 /* If non-blocking got this far - and failed - assume non-blocking is
3147 not supported after all. This is probably a wrong assumption, but
3148 the normal blocking calls to open-network-stream handles this error
3149 better. */
3150 if (is_non_blocking_client)
3151 return Qnil;
3153 errno = xerrno;
3154 if (is_server)
3155 report_file_error ("make server process failed", contact);
3156 else
3157 report_file_error ("make client process failed", contact);
3160 tem = Fplist_get (contact, QCoptions);
3161 if (!NILP (tem))
3162 set_socket_options (s, tem, 1);
3164 #endif /* not TERM */
3166 inch = s;
3167 outch = s;
3169 if (!NILP (buffer))
3170 buffer = Fget_buffer_create (buffer);
3171 proc = make_process (name);
3173 chan_process[inch] = proc;
3175 #ifdef O_NONBLOCK
3176 fcntl (inch, F_SETFL, O_NONBLOCK);
3177 #else
3178 #ifdef O_NDELAY
3179 fcntl (inch, F_SETFL, O_NDELAY);
3180 #endif
3181 #endif
3183 p = XPROCESS (proc);
3185 p->childp = contact;
3186 p->private_vars = Fcopy_sequence (Fplist_get (contact, QCvars));
3188 p->buffer = buffer;
3189 p->sentinel = sentinel;
3190 p->filter = filter;
3191 p->log = Fplist_get (contact, QClog);
3192 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3193 p->kill_without_query = Qt;
3194 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3195 p->command = Qt;
3196 p->pid = Qnil;
3197 XSETINT (p->infd, inch);
3198 XSETINT (p->outfd, outch);
3199 if (is_server && socktype == SOCK_STREAM)
3200 p->status = Qlisten;
3202 #ifdef NON_BLOCKING_CONNECT
3203 if (is_non_blocking_client)
3205 /* We may get here if connect did succeed immediately. However,
3206 in that case, we still need to signal this like a non-blocking
3207 connection. */
3208 p->status = Qconnect;
3209 if (!FD_ISSET (inch, &connect_wait_mask))
3211 FD_SET (inch, &connect_wait_mask);
3212 num_pending_connects++;
3215 else
3216 #endif
3217 /* A server may have a client filter setting of Qt, but it must
3218 still listen for incoming connects unless it is stopped. */
3219 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3220 || (EQ (p->status, Qlisten) && NILP (p->command)))
3222 FD_SET (inch, &input_wait_mask);
3223 FD_SET (inch, &non_keyboard_wait_mask);
3226 if (inch > max_process_desc)
3227 max_process_desc = inch;
3229 tem = Fplist_member (contact, QCcoding);
3230 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3231 tem = Qnil; /* No error message (too late!). */
3234 /* Setup coding systems for communicating with the network stream. */
3235 struct gcpro gcpro1;
3236 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3237 Lisp_Object coding_systems = Qt;
3238 Lisp_Object args[5], val;
3240 if (!NILP (tem))
3241 val = XCAR (XCDR (tem));
3242 else if (!NILP (Vcoding_system_for_read))
3243 val = Vcoding_system_for_read;
3244 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3245 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3246 /* We dare not decode end-of-line format by setting VAL to
3247 Qraw_text, because the existing Emacs Lisp libraries
3248 assume that they receive bare code including a sequene of
3249 CR LF. */
3250 val = Qnil;
3251 else
3253 if (NILP (host) || NILP (service))
3254 coding_systems = Qnil;
3255 else
3257 args[0] = Qopen_network_stream, args[1] = name,
3258 args[2] = buffer, args[3] = host, args[4] = service;
3259 GCPRO1 (proc);
3260 coding_systems = Ffind_operation_coding_system (5, args);
3261 UNGCPRO;
3263 if (CONSP (coding_systems))
3264 val = XCAR (coding_systems);
3265 else if (CONSP (Vdefault_process_coding_system))
3266 val = XCAR (Vdefault_process_coding_system);
3267 else
3268 val = Qnil;
3270 p->decode_coding_system = val;
3272 if (!NILP (tem))
3273 val = XCAR (XCDR (tem));
3274 else if (!NILP (Vcoding_system_for_write))
3275 val = Vcoding_system_for_write;
3276 else if (NILP (current_buffer->enable_multibyte_characters))
3277 val = Qnil;
3278 else
3280 if (EQ (coding_systems, Qt))
3282 if (NILP (host) || NILP (service))
3283 coding_systems = Qnil;
3284 else
3286 args[0] = Qopen_network_stream, args[1] = name,
3287 args[2] = buffer, args[3] = host, args[4] = service;
3288 GCPRO1 (proc);
3289 coding_systems = Ffind_operation_coding_system (5, args);
3290 UNGCPRO;
3293 if (CONSP (coding_systems))
3294 val = XCDR (coding_systems);
3295 else if (CONSP (Vdefault_process_coding_system))
3296 val = XCDR (Vdefault_process_coding_system);
3297 else
3298 val = Qnil;
3300 p->encode_coding_system = val;
3303 if (!proc_decode_coding_system[inch])
3304 proc_decode_coding_system[inch]
3305 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
3306 setup_coding_system (p->decode_coding_system,
3307 proc_decode_coding_system[inch]);
3308 if (!proc_encode_coding_system[outch])
3309 proc_encode_coding_system[outch]
3310 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
3311 setup_coding_system (p->encode_coding_system,
3312 proc_encode_coding_system[outch]);
3314 p->decoding_buf = make_uninit_string (0);
3315 p->decoding_carryover = make_number (0);
3316 p->encoding_buf = make_uninit_string (0);
3317 p->encoding_carryover = make_number (0);
3319 p->inherit_coding_system_flag
3320 = (!NILP (tem) || NILP (buffer) || !inherit_process_coding_system
3321 ? Qnil : Qt);
3323 UNGCPRO;
3324 return proc;
3326 #endif /* HAVE_SOCKETS */
3328 void
3329 deactivate_process (proc)
3330 Lisp_Object proc;
3332 register int inchannel, outchannel;
3333 register struct Lisp_Process *p = XPROCESS (proc);
3335 inchannel = XINT (p->infd);
3336 outchannel = XINT (p->outfd);
3338 if (inchannel >= 0)
3340 /* Beware SIGCHLD hereabouts. */
3341 flush_pending_output (inchannel);
3342 #ifdef VMS
3344 VMS_PROC_STUFF *get_vms_process_pointer (), *vs;
3345 sys$dassgn (outchannel);
3346 vs = get_vms_process_pointer (p->pid);
3347 if (vs)
3348 give_back_vms_process_stuff (vs);
3350 #else
3351 emacs_close (inchannel);
3352 if (outchannel >= 0 && outchannel != inchannel)
3353 emacs_close (outchannel);
3354 #endif
3356 XSETINT (p->infd, -1);
3357 XSETINT (p->outfd, -1);
3358 #ifdef DATAGRAM_SOCKETS
3359 if (DATAGRAM_CHAN_P (inchannel))
3361 xfree (datagram_address[inchannel].sa);
3362 datagram_address[inchannel].sa = 0;
3363 datagram_address[inchannel].len = 0;
3365 #endif
3366 chan_process[inchannel] = Qnil;
3367 FD_CLR (inchannel, &input_wait_mask);
3368 FD_CLR (inchannel, &non_keyboard_wait_mask);
3369 if (FD_ISSET (inchannel, &connect_wait_mask))
3371 FD_CLR (inchannel, &connect_wait_mask);
3372 if (--num_pending_connects < 0)
3373 abort ();
3375 if (inchannel == max_process_desc)
3377 int i;
3378 /* We just closed the highest-numbered process input descriptor,
3379 so recompute the highest-numbered one now. */
3380 max_process_desc = 0;
3381 for (i = 0; i < MAXDESC; i++)
3382 if (!NILP (chan_process[i]))
3383 max_process_desc = i;
3388 /* Close all descriptors currently in use for communication
3389 with subprocess. This is used in a newly-forked subprocess
3390 to get rid of irrelevant descriptors. */
3392 void
3393 close_process_descs ()
3395 #ifndef WINDOWSNT
3396 int i;
3397 for (i = 0; i < MAXDESC; i++)
3399 Lisp_Object process;
3400 process = chan_process[i];
3401 if (!NILP (process))
3403 int in = XINT (XPROCESS (process)->infd);
3404 int out = XINT (XPROCESS (process)->outfd);
3405 if (in >= 0)
3406 emacs_close (in);
3407 if (out >= 0 && in != out)
3408 emacs_close (out);
3411 #endif
3414 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
3415 0, 3, 0,
3416 doc: /* Allow any pending output from subprocesses to be read by Emacs.
3417 It is read into the process' buffers or given to their filter functions.
3418 Non-nil arg PROCESS means do not return until some output has been received
3419 from PROCESS.
3420 Non-nil second arg TIMEOUT and third arg TIMEOUT-MSECS are number of
3421 seconds and microseconds to wait; return after that much time whether
3422 or not there is input.
3423 Return non-nil iff we received any output before the timeout expired. */)
3424 (process, timeout, timeout_msecs)
3425 register Lisp_Object process, timeout, timeout_msecs;
3427 int seconds;
3428 int useconds;
3430 if (! NILP (process))
3431 CHECK_PROCESS (process);
3433 if (! NILP (timeout_msecs))
3435 CHECK_NUMBER (timeout_msecs);
3436 useconds = XINT (timeout_msecs);
3437 if (!INTEGERP (timeout))
3438 XSETINT (timeout, 0);
3441 int carry = useconds / 1000000;
3443 XSETINT (timeout, XINT (timeout) + carry);
3444 useconds -= carry * 1000000;
3446 /* I think this clause is necessary because C doesn't
3447 guarantee a particular rounding direction for negative
3448 integers. */
3449 if (useconds < 0)
3451 XSETINT (timeout, XINT (timeout) - 1);
3452 useconds += 1000000;
3456 else
3457 useconds = 0;
3459 if (! NILP (timeout))
3461 CHECK_NUMBER (timeout);
3462 seconds = XINT (timeout);
3463 if (seconds < 0 || (seconds == 0 && useconds == 0))
3464 seconds = -1;
3466 else
3468 if (NILP (process))
3469 seconds = -1;
3470 else
3471 seconds = 0;
3474 if (NILP (process))
3475 XSETFASTINT (process, 0);
3477 return
3478 (wait_reading_process_input (seconds, useconds, process, 0)
3479 ? Qt : Qnil);
3482 /* Accept a connection for server process SERVER on CHANNEL. */
3484 static int connect_counter = 0;
3486 static void
3487 server_accept_connection (server, channel)
3488 Lisp_Object server;
3489 int channel;
3491 Lisp_Object proc, caller, name, buffer;
3492 Lisp_Object contact, host, service;
3493 struct Lisp_Process *ps= XPROCESS (server);
3494 struct Lisp_Process *p;
3495 int s;
3496 union u_sockaddr {
3497 struct sockaddr sa;
3498 struct sockaddr_in in;
3499 #ifdef HAVE_LOCAL_SOCKETS
3500 struct sockaddr_un un;
3501 #endif
3502 } saddr;
3503 int len = sizeof saddr;
3505 s = accept (channel, &saddr.sa, &len);
3507 if (s < 0)
3509 int code = errno;
3511 if (code == EAGAIN)
3512 return;
3513 #ifdef EWOULDBLOCK
3514 if (code == EWOULDBLOCK)
3515 return;
3516 #endif
3518 if (!NILP (ps->log))
3519 call3 (ps->log, server, Qnil,
3520 concat3 (build_string ("accept failed with code"),
3521 Fnumber_to_string (make_number (code)),
3522 build_string ("\n")));
3523 return;
3526 connect_counter++;
3528 /* Setup a new process to handle the connection. */
3530 /* Generate a unique identification of the caller, and build contact
3531 information for this process. */
3532 host = Qt;
3533 service = Qnil;
3534 switch (saddr.sa.sa_family)
3536 case AF_INET:
3538 Lisp_Object args[5];
3539 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
3540 args[0] = build_string ("%d.%d.%d.%d");
3541 args[1] = make_number (*ip++);
3542 args[2] = make_number (*ip++);
3543 args[3] = make_number (*ip++);
3544 args[4] = make_number (*ip++);
3545 host = Fformat (5, args);
3546 service = make_number (ntohs (saddr.in.sin_port));
3548 args[0] = build_string (" <%s:%d>");
3549 args[1] = host;
3550 args[2] = service;
3551 caller = Fformat (3, args);
3553 break;
3555 #ifdef HAVE_LOCAL_SOCKETS
3556 case AF_LOCAL:
3557 #endif
3558 default:
3559 caller = Fnumber_to_string (make_number (connect_counter));
3560 caller = concat3 (build_string (" <*"), caller, build_string ("*>"));
3561 break;
3564 /* Create a new buffer name for this process if it doesn't have a
3565 filter. The new buffer name is based on the buffer name or
3566 process name of the server process concatenated with the caller
3567 identification. */
3569 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
3570 buffer = Qnil;
3571 else
3573 buffer = ps->buffer;
3574 if (!NILP (buffer))
3575 buffer = Fbuffer_name (buffer);
3576 else
3577 buffer = ps->name;
3578 if (!NILP (buffer))
3580 buffer = concat2 (buffer, caller);
3581 buffer = Fget_buffer_create (buffer);
3585 /* Generate a unique name for the new server process. Combine the
3586 server process name with the caller identification. */
3588 name = concat2 (ps->name, caller);
3589 proc = make_process (name);
3591 chan_process[s] = proc;
3593 #ifdef O_NONBLOCK
3594 fcntl (s, F_SETFL, O_NONBLOCK);
3595 #else
3596 #ifdef O_NDELAY
3597 fcntl (s, F_SETFL, O_NDELAY);
3598 #endif
3599 #endif
3601 p = XPROCESS (proc);
3603 /* Build new contact information for this setup. */
3604 contact = Fcopy_sequence (ps->childp);
3605 contact = Fplist_put (contact, QCserver, Qnil);
3606 contact = Fplist_put (contact, QChost, host);
3607 if (!NILP (service))
3608 contact = Fplist_put (contact, QCservice, service);
3609 contact = Fplist_put (contact, QCremote,
3610 conv_sockaddr_to_lisp (&saddr.sa, len));
3611 #ifdef HAVE_GETSOCKNAME
3612 len = sizeof saddr;
3613 if (getsockname (s, &saddr.sa, &len) == 0)
3614 contact = Fplist_put (contact, QClocal,
3615 conv_sockaddr_to_lisp (&saddr.sa, len));
3616 #endif
3618 p->childp = contact;
3619 p->private_vars = Fcopy_sequence (ps->private_vars);
3621 p->buffer = buffer;
3622 p->sentinel = ps->sentinel;
3623 p->filter = ps->filter;
3624 p->command = Qnil;
3625 p->pid = Qnil;
3626 XSETINT (p->infd, s);
3627 XSETINT (p->outfd, s);
3628 p->status = Qrun;
3630 /* Client processes for accepted connections are not stopped initially. */
3631 if (!EQ (p->filter, Qt))
3633 FD_SET (s, &input_wait_mask);
3634 FD_SET (s, &non_keyboard_wait_mask);
3637 if (s > max_process_desc)
3638 max_process_desc = s;
3640 /* Setup coding system for new process based on server process.
3641 This seems to be the proper thing to do, as the coding system
3642 of the new process should reflect the settings at the time the
3643 server socket was opened; not the current settings. */
3645 p->decode_coding_system = ps->decode_coding_system;
3646 p->encode_coding_system = ps->encode_coding_system;
3648 if (!proc_decode_coding_system[s])
3649 proc_decode_coding_system[s]
3650 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
3651 setup_coding_system (p->decode_coding_system,
3652 proc_decode_coding_system[s]);
3653 if (!proc_encode_coding_system[s])
3654 proc_encode_coding_system[s]
3655 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
3656 setup_coding_system (p->encode_coding_system,
3657 proc_encode_coding_system[s]);
3659 p->decoding_buf = make_uninit_string (0);
3660 p->decoding_carryover = make_number (0);
3661 p->encoding_buf = make_uninit_string (0);
3662 p->encoding_carryover = make_number (0);
3664 p->inherit_coding_system_flag
3665 = (NILP (buffer) ? Qnil : ps->inherit_coding_system_flag);
3667 if (!NILP (ps->log))
3668 call3 (ps->log, server, proc,
3669 concat3 (build_string ("accept from "),
3670 (STRINGP (host) ? host : build_string ("-")),
3671 build_string ("\n")));
3673 if (!NILP (p->sentinel))
3674 exec_sentinel (proc,
3675 concat3 (build_string ("open from "),
3676 (STRINGP (host) ? host : build_string ("-")),
3677 build_string ("\n")));
3680 /* This variable is different from waiting_for_input in keyboard.c.
3681 It is used to communicate to a lisp process-filter/sentinel (via the
3682 function Fwaiting_for_user_input_p below) whether emacs was waiting
3683 for user-input when that process-filter was called.
3684 waiting_for_input cannot be used as that is by definition 0 when
3685 lisp code is being evalled.
3686 This is also used in record_asynch_buffer_change.
3687 For that purpose, this must be 0
3688 when not inside wait_reading_process_input. */
3689 static int waiting_for_user_input_p;
3691 /* This is here so breakpoints can be put on it. */
3692 static void
3693 wait_reading_process_input_1 ()
3697 /* Read and dispose of subprocess output while waiting for timeout to
3698 elapse and/or keyboard input to be available.
3700 TIME_LIMIT is:
3701 timeout in seconds, or
3702 zero for no limit, or
3703 -1 means gobble data immediately available but don't wait for any.
3705 MICROSECS is:
3706 an additional duration to wait, measured in microseconds.
3707 If this is nonzero and time_limit is 0, then the timeout
3708 consists of MICROSECS only.
3710 READ_KBD is a lisp value:
3711 0 to ignore keyboard input, or
3712 1 to return when input is available, or
3713 -1 meaning caller will actually read the input, so don't throw to
3714 the quit handler, or
3715 a cons cell, meaning wait until its car is non-nil
3716 (and gobble terminal input into the buffer if any arrives), or
3717 a process object, meaning wait until something arrives from that
3718 process. The return value is true iff we read some input from
3719 that process.
3721 DO_DISPLAY != 0 means redisplay should be done to show subprocess
3722 output that arrives.
3724 If READ_KBD is a pointer to a struct Lisp_Process, then the
3725 function returns true iff we received input from that process
3726 before the timeout elapsed.
3727 Otherwise, return true iff we received input from any process. */
3730 wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
3731 int time_limit, microsecs;
3732 Lisp_Object read_kbd;
3733 int do_display;
3735 register int channel, nfds;
3736 static SELECT_TYPE Available;
3737 static SELECT_TYPE Connecting;
3738 int check_connect, no_avail;
3739 int xerrno;
3740 Lisp_Object proc;
3741 EMACS_TIME timeout, end_time;
3742 int wait_channel = -1;
3743 struct Lisp_Process *wait_proc = 0;
3744 int got_some_input = 0;
3745 /* Either nil or a cons cell, the car of which is of interest and
3746 may be changed outside of this routine. */
3747 Lisp_Object wait_for_cell = Qnil;
3749 FD_ZERO (&Available);
3750 FD_ZERO (&Connecting);
3752 /* If read_kbd is a process to watch, set wait_proc and wait_channel
3753 accordingly. */
3754 if (PROCESSP (read_kbd))
3756 wait_proc = XPROCESS (read_kbd);
3757 wait_channel = XINT (wait_proc->infd);
3758 XSETFASTINT (read_kbd, 0);
3761 /* If waiting for non-nil in a cell, record where. */
3762 if (CONSP (read_kbd))
3764 wait_for_cell = read_kbd;
3765 XSETFASTINT (read_kbd, 0);
3768 waiting_for_user_input_p = XINT (read_kbd);
3770 /* Since we may need to wait several times,
3771 compute the absolute time to return at. */
3772 if (time_limit || microsecs)
3774 EMACS_GET_TIME (end_time);
3775 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
3776 EMACS_ADD_TIME (end_time, end_time, timeout);
3778 #ifdef POLLING_PROBLEM_IN_SELECT
3779 /* AlainF 5-Jul-1996
3780 HP-UX 10.10 seem to have problems with signals coming in
3781 Causes "poll: interrupted system call" messages when Emacs is run
3782 in an X window
3783 Turn off periodic alarms (in case they are in use),
3784 and then turn off any other atimers. */
3785 stop_polling ();
3786 turn_on_atimers (0);
3787 #endif
3789 while (1)
3791 int timeout_reduced_for_timers = 0;
3793 /* If calling from keyboard input, do not quit
3794 since we want to return C-g as an input character.
3795 Otherwise, do pending quit if requested. */
3796 if (XINT (read_kbd) >= 0)
3797 QUIT;
3799 /* Exit now if the cell we're waiting for became non-nil. */
3800 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
3801 break;
3803 /* Compute time from now till when time limit is up */
3804 /* Exit if already run out */
3805 if (time_limit == -1)
3807 /* -1 specified for timeout means
3808 gobble output available now
3809 but don't wait at all. */
3811 EMACS_SET_SECS_USECS (timeout, 0, 0);
3813 else if (time_limit || microsecs)
3815 EMACS_GET_TIME (timeout);
3816 EMACS_SUB_TIME (timeout, end_time, timeout);
3817 if (EMACS_TIME_NEG_P (timeout))
3818 break;
3820 else
3822 EMACS_SET_SECS_USECS (timeout, 100000, 0);
3825 /* Normally we run timers here.
3826 But not if wait_for_cell; in those cases,
3827 the wait is supposed to be short,
3828 and those callers cannot handle running arbitrary Lisp code here. */
3829 if (NILP (wait_for_cell))
3831 EMACS_TIME timer_delay;
3835 int old_timers_run = timers_run;
3836 struct buffer *old_buffer = current_buffer;
3838 timer_delay = timer_check (1);
3840 /* If a timer has run, this might have changed buffers
3841 an alike. Make read_key_sequence aware of that. */
3842 if (timers_run != old_timers_run
3843 && old_buffer != current_buffer
3844 && waiting_for_user_input_p == -1)
3845 record_asynch_buffer_change ();
3847 if (timers_run != old_timers_run && do_display)
3848 /* We must retry, since a timer may have requeued itself
3849 and that could alter the time_delay. */
3850 redisplay_preserve_echo_area (9);
3851 else
3852 break;
3854 while (!detect_input_pending ());
3856 /* If there is unread keyboard input, also return. */
3857 if (XINT (read_kbd) != 0
3858 && requeued_events_pending_p ())
3859 break;
3861 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
3863 EMACS_TIME difference;
3864 EMACS_SUB_TIME (difference, timer_delay, timeout);
3865 if (EMACS_TIME_NEG_P (difference))
3867 timeout = timer_delay;
3868 timeout_reduced_for_timers = 1;
3871 /* If time_limit is -1, we are not going to wait at all. */
3872 else if (time_limit != -1)
3874 /* This is so a breakpoint can be put here. */
3875 wait_reading_process_input_1 ();
3879 /* Cause C-g and alarm signals to take immediate action,
3880 and cause input available signals to zero out timeout.
3882 It is important that we do this before checking for process
3883 activity. If we get a SIGCHLD after the explicit checks for
3884 process activity, timeout is the only way we will know. */
3885 if (XINT (read_kbd) < 0)
3886 set_waiting_for_input (&timeout);
3888 /* If status of something has changed, and no input is
3889 available, notify the user of the change right away. After
3890 this explicit check, we'll let the SIGCHLD handler zap
3891 timeout to get our attention. */
3892 if (update_tick != process_tick && do_display)
3894 SELECT_TYPE Atemp, Ctemp;
3896 Atemp = input_wait_mask;
3897 #ifdef MAC_OSX
3898 /* On Mac OS X, the SELECT system call always says input is
3899 present (for reading) at stdin, even when none is. This
3900 causes the call to SELECT below to return 1 and
3901 status_notify not to be called. As a result output of
3902 subprocesses are incorrectly discarded. */
3903 FD_CLR (0, &Atemp);
3904 #endif
3905 Ctemp = connect_wait_mask;
3906 EMACS_SET_SECS_USECS (timeout, 0, 0);
3907 if ((select (max (max_process_desc, max_keyboard_desc) + 1,
3908 &Atemp,
3909 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
3910 (SELECT_TYPE *)0, &timeout)
3911 <= 0))
3913 /* It's okay for us to do this and then continue with
3914 the loop, since timeout has already been zeroed out. */
3915 clear_waiting_for_input ();
3916 status_notify ();
3920 /* Don't wait for output from a non-running process. Just
3921 read whatever data has already been received. */
3922 if (wait_proc != 0 && !NILP (wait_proc->raw_status_low))
3923 update_status (wait_proc);
3924 if (wait_proc != 0
3925 && ! EQ (wait_proc->status, Qrun)
3926 && ! EQ (wait_proc->status, Qconnect))
3928 int nread, total_nread = 0;
3930 clear_waiting_for_input ();
3931 XSETPROCESS (proc, wait_proc);
3933 /* Read data from the process, until we exhaust it. */
3934 while (XINT (wait_proc->infd) >= 0)
3936 nread = read_process_output (proc, XINT (wait_proc->infd));
3938 if (nread == 0)
3939 break;
3941 if (0 < nread)
3942 total_nread += nread;
3943 #ifdef EIO
3944 else if (nread == -1 && EIO == errno)
3945 break;
3946 #endif
3947 #ifdef EAGAIN
3948 else if (nread == -1 && EAGAIN == errno)
3949 break;
3950 #endif
3951 #ifdef EWOULDBLOCK
3952 else if (nread == -1 && EWOULDBLOCK == errno)
3953 break;
3954 #endif
3956 if (total_nread > 0 && do_display)
3957 redisplay_preserve_echo_area (10);
3959 break;
3962 /* Wait till there is something to do */
3964 if (!NILP (wait_for_cell))
3966 Available = non_process_wait_mask;
3967 check_connect = 0;
3969 else
3971 if (! XINT (read_kbd))
3972 Available = non_keyboard_wait_mask;
3973 else
3974 Available = input_wait_mask;
3975 check_connect = (num_pending_connects > 0);
3978 /* If frame size has changed or the window is newly mapped,
3979 redisplay now, before we start to wait. There is a race
3980 condition here; if a SIGIO arrives between now and the select
3981 and indicates that a frame is trashed, the select may block
3982 displaying a trashed screen. */
3983 if (frame_garbaged && do_display)
3985 clear_waiting_for_input ();
3986 redisplay_preserve_echo_area (11);
3987 if (XINT (read_kbd) < 0)
3988 set_waiting_for_input (&timeout);
3991 no_avail = 0;
3992 if (XINT (read_kbd) && detect_input_pending ())
3994 nfds = 0;
3995 no_avail = 1;
3997 else
3999 if (check_connect)
4000 Connecting = connect_wait_mask;
4001 nfds = select (max (max_process_desc, max_keyboard_desc) + 1,
4002 &Available,
4003 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4004 (SELECT_TYPE *)0, &timeout);
4007 xerrno = errno;
4009 /* Make C-g and alarm signals set flags again */
4010 clear_waiting_for_input ();
4012 /* If we woke up due to SIGWINCH, actually change size now. */
4013 do_pending_window_change (0);
4015 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4016 /* We wanted the full specified time, so return now. */
4017 break;
4018 if (nfds < 0)
4020 if (xerrno == EINTR)
4021 no_avail = 1;
4022 #ifdef ultrix
4023 /* Ultrix select seems to return ENOMEM when it is
4024 interrupted. Treat it just like EINTR. Bleah. Note
4025 that we want to test for the "ultrix" CPP symbol, not
4026 "__ultrix__"; the latter is only defined under GCC, but
4027 not by DEC's bundled CC. -JimB */
4028 else if (xerrno == ENOMEM)
4029 no_avail = 1;
4030 #endif
4031 #ifdef ALLIANT
4032 /* This happens for no known reason on ALLIANT.
4033 I am guessing that this is the right response. -- RMS. */
4034 else if (xerrno == EFAULT)
4035 no_avail = 1;
4036 #endif
4037 else if (xerrno == EBADF)
4039 #ifdef AIX
4040 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4041 the child's closure of the pts gives the parent a SIGHUP, and
4042 the ptc file descriptor is automatically closed,
4043 yielding EBADF here or at select() call above.
4044 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4045 in m/ibmrt-aix.h), and here we just ignore the select error.
4046 Cleanup occurs c/o status_notify after SIGCLD. */
4047 no_avail = 1; /* Cannot depend on values returned */
4048 #else
4049 abort ();
4050 #endif
4052 else
4053 error ("select error: %s", emacs_strerror (xerrno));
4056 if (no_avail)
4058 FD_ZERO (&Available);
4059 check_connect = 0;
4062 #if defined(sun) && !defined(USG5_4)
4063 if (nfds > 0 && keyboard_bit_set (&Available)
4064 && interrupt_input)
4065 /* System sometimes fails to deliver SIGIO.
4067 David J. Mackenzie says that Emacs doesn't compile under
4068 Solaris if this code is enabled, thus the USG5_4 in the CPP
4069 conditional. "I haven't noticed any ill effects so far.
4070 If you find a Solaris expert somewhere, they might know
4071 better." */
4072 kill (getpid (), SIGIO);
4073 #endif
4075 #if 0 /* When polling is used, interrupt_input is 0,
4076 so get_input_pending should read the input.
4077 So this should not be needed. */
4078 /* If we are using polling for input,
4079 and we see input available, make it get read now.
4080 Otherwise it might not actually get read for a second.
4081 And on hpux, since we turn off polling in wait_reading_process_input,
4082 it might never get read at all if we don't spend much time
4083 outside of wait_reading_process_input. */
4084 if (XINT (read_kbd) && interrupt_input
4085 && keyboard_bit_set (&Available)
4086 && input_polling_used ())
4087 kill (getpid (), SIGALRM);
4088 #endif
4090 /* Check for keyboard input */
4091 /* If there is any, return immediately
4092 to give it higher priority than subprocesses */
4094 if (XINT (read_kbd) != 0)
4096 int old_timers_run = timers_run;
4097 struct buffer *old_buffer = current_buffer;
4098 int leave = 0;
4100 if (detect_input_pending_run_timers (do_display))
4102 swallow_events (do_display);
4103 if (detect_input_pending_run_timers (do_display))
4104 leave = 1;
4107 /* If a timer has run, this might have changed buffers
4108 an alike. Make read_key_sequence aware of that. */
4109 if (timers_run != old_timers_run
4110 && waiting_for_user_input_p == -1
4111 && old_buffer != current_buffer)
4112 record_asynch_buffer_change ();
4114 if (leave)
4115 break;
4118 /* If there is unread keyboard input, also return. */
4119 if (XINT (read_kbd) != 0
4120 && requeued_events_pending_p ())
4121 break;
4123 /* If we are not checking for keyboard input now,
4124 do process events (but don't run any timers).
4125 This is so that X events will be processed.
4126 Otherwise they may have to wait until polling takes place.
4127 That would causes delays in pasting selections, for example.
4129 (We used to do this only if wait_for_cell.) */
4130 if (XINT (read_kbd) == 0 && detect_input_pending ())
4132 swallow_events (do_display);
4133 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4134 if (detect_input_pending ())
4135 break;
4136 #endif
4139 /* Exit now if the cell we're waiting for became non-nil. */
4140 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4141 break;
4143 #ifdef SIGIO
4144 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4145 go read it. This can happen with X on BSD after logging out.
4146 In that case, there really is no input and no SIGIO,
4147 but select says there is input. */
4149 if (XINT (read_kbd) && interrupt_input
4150 && keyboard_bit_set (&Available))
4151 kill (getpid (), SIGIO);
4152 #endif
4154 if (! wait_proc)
4155 got_some_input |= nfds > 0;
4157 /* If checking input just got us a size-change event from X,
4158 obey it now if we should. */
4159 if (XINT (read_kbd) || ! NILP (wait_for_cell))
4160 do_pending_window_change (0);
4162 /* Check for data from a process. */
4163 if (no_avail || nfds == 0)
4164 continue;
4166 /* Really FIRST_PROC_DESC should be 0 on Unix,
4167 but this is safer in the short run. */
4168 for (channel = 0; channel <= max_process_desc; channel++)
4170 if (FD_ISSET (channel, &Available)
4171 && FD_ISSET (channel, &non_keyboard_wait_mask))
4173 int nread;
4175 /* If waiting for this channel, arrange to return as
4176 soon as no more input to be processed. No more
4177 waiting. */
4178 if (wait_channel == channel)
4180 wait_channel = -1;
4181 time_limit = -1;
4182 got_some_input = 1;
4184 proc = chan_process[channel];
4185 if (NILP (proc))
4186 continue;
4188 /* If this is a server stream socket, accept connection. */
4189 if (EQ (XPROCESS (proc)->status, Qlisten))
4191 server_accept_connection (proc, channel);
4192 continue;
4195 /* Read data from the process, starting with our
4196 buffered-ahead character if we have one. */
4198 nread = read_process_output (proc, channel);
4199 if (nread > 0)
4201 /* Since read_process_output can run a filter,
4202 which can call accept-process-output,
4203 don't try to read from any other processes
4204 before doing the select again. */
4205 FD_ZERO (&Available);
4207 if (do_display)
4208 redisplay_preserve_echo_area (12);
4210 #ifdef EWOULDBLOCK
4211 else if (nread == -1 && errno == EWOULDBLOCK)
4213 #endif
4214 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4215 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4216 #ifdef O_NONBLOCK
4217 else if (nread == -1 && errno == EAGAIN)
4219 #else
4220 #ifdef O_NDELAY
4221 else if (nread == -1 && errno == EAGAIN)
4223 /* Note that we cannot distinguish between no input
4224 available now and a closed pipe.
4225 With luck, a closed pipe will be accompanied by
4226 subprocess termination and SIGCHLD. */
4227 else if (nread == 0 && !NETCONN_P (proc))
4229 #endif /* O_NDELAY */
4230 #endif /* O_NONBLOCK */
4231 #ifdef HAVE_PTYS
4232 /* On some OSs with ptys, when the process on one end of
4233 a pty exits, the other end gets an error reading with
4234 errno = EIO instead of getting an EOF (0 bytes read).
4235 Therefore, if we get an error reading and errno =
4236 EIO, just continue, because the child process has
4237 exited and should clean itself up soon (e.g. when we
4238 get a SIGCHLD).
4240 However, it has been known to happen that the SIGCHLD
4241 got lost. So raise the signl again just in case.
4242 It can't hurt. */
4243 else if (nread == -1 && errno == EIO)
4244 kill (getpid (), SIGCHLD);
4245 #endif /* HAVE_PTYS */
4246 /* If we can detect process termination, don't consider the process
4247 gone just because its pipe is closed. */
4248 #ifdef SIGCHLD
4249 else if (nread == 0 && !NETCONN_P (proc))
4251 #endif
4252 else
4254 /* Preserve status of processes already terminated. */
4255 XSETINT (XPROCESS (proc)->tick, ++process_tick);
4256 deactivate_process (proc);
4257 if (!NILP (XPROCESS (proc)->raw_status_low))
4258 update_status (XPROCESS (proc));
4259 if (EQ (XPROCESS (proc)->status, Qrun))
4260 XPROCESS (proc)->status
4261 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4264 #ifdef NON_BLOCKING_CONNECT
4265 if (check_connect && FD_ISSET (channel, &Connecting))
4267 struct Lisp_Process *p;
4269 FD_CLR (channel, &connect_wait_mask);
4270 if (--num_pending_connects < 0)
4271 abort ();
4273 proc = chan_process[channel];
4274 if (NILP (proc))
4275 continue;
4277 p = XPROCESS (proc);
4279 #ifdef GNU_LINUX
4280 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4281 So only use it on systems where it is known to work. */
4283 int xlen = sizeof(xerrno);
4284 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4285 xerrno = errno;
4287 #else
4289 struct sockaddr pname;
4290 int pnamelen = sizeof(pname);
4292 /* If connection failed, getpeername will fail. */
4293 xerrno = 0;
4294 if (getpeername(channel, &pname, &pnamelen) < 0)
4296 /* Obtain connect failure code through error slippage. */
4297 char dummy;
4298 xerrno = errno;
4299 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
4300 xerrno = errno;
4303 #endif
4304 if (xerrno)
4306 XSETINT (p->tick, ++process_tick);
4307 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
4308 deactivate_process (proc);
4310 else
4312 p->status = Qrun;
4313 /* Execute the sentinel here. If we had relied on
4314 status_notify to do it later, it will read input
4315 from the process before calling the sentinel. */
4316 exec_sentinel (proc, build_string ("open\n"));
4317 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4319 FD_SET (XINT (p->infd), &input_wait_mask);
4320 FD_SET (XINT (p->infd), &non_keyboard_wait_mask);
4324 #endif /* NON_BLOCKING_CONNECT */
4325 } /* end for each file descriptor */
4326 } /* end while exit conditions not met */
4328 waiting_for_user_input_p = 0;
4330 /* If calling from keyboard input, do not quit
4331 since we want to return C-g as an input character.
4332 Otherwise, do pending quit if requested. */
4333 if (XINT (read_kbd) >= 0)
4335 /* Prevent input_pending from remaining set if we quit. */
4336 clear_input_pending ();
4337 QUIT;
4339 #ifdef hpux
4340 /* AlainF 5-Jul-1996
4341 HP-UX 10.10 seems to have problems with signals coming in
4342 Causes "poll: interrupted system call" messages when Emacs is run
4343 in an X window
4344 Turn periodic alarms back on */
4345 start_polling ();
4346 #endif
4348 return got_some_input;
4351 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4353 static Lisp_Object
4354 read_process_output_call (fun_and_args)
4355 Lisp_Object fun_and_args;
4357 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4360 static Lisp_Object
4361 read_process_output_error_handler (error)
4362 Lisp_Object error;
4364 cmd_error_internal (error, "error in process filter: ");
4365 Vinhibit_quit = Qt;
4366 update_echo_area ();
4367 Fsleep_for (make_number (2), Qnil);
4368 return Qt;
4371 /* Read pending output from the process channel,
4372 starting with our buffered-ahead character if we have one.
4373 Yield number of decoded characters read.
4375 This function reads at most 1024 characters.
4376 If you want to read all available subprocess output,
4377 you must call it repeatedly until it returns zero.
4379 The characters read are decoded according to PROC's coding-system
4380 for decoding. */
4383 read_process_output (proc, channel)
4384 Lisp_Object proc;
4385 register int channel;
4387 register int nchars, nbytes;
4388 char *chars;
4389 register Lisp_Object outstream;
4390 register struct buffer *old = current_buffer;
4391 register struct Lisp_Process *p = XPROCESS (proc);
4392 register int opoint;
4393 struct coding_system *coding = proc_decode_coding_system[channel];
4394 int carryover = XINT (p->decoding_carryover);
4395 int readmax = 1024;
4397 #ifdef VMS
4398 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
4400 vs = get_vms_process_pointer (p->pid);
4401 if (vs)
4403 if (!vs->iosb[0])
4404 return (0); /* Really weird if it does this */
4405 if (!(vs->iosb[0] & 1))
4406 return -1; /* I/O error */
4408 else
4409 error ("Could not get VMS process pointer");
4410 chars = vs->inputBuffer;
4411 nbytes = clean_vms_buffer (chars, vs->iosb[1]);
4412 if (nbytes <= 0)
4414 start_vms_process_read (vs); /* Crank up the next read on the process */
4415 return 1; /* Nothing worth printing, say we got 1 */
4417 if (carryover > 0)
4419 /* The data carried over in the previous decoding (which are at
4420 the tail of decoding buffer) should be prepended to the new
4421 data read to decode all together. */
4422 chars = (char *) alloca (nbytes + carryover);
4423 bcopy (SDATA (p->decoding_buf), buf, carryover);
4424 bcopy (vs->inputBuffer, chars + carryover, nbytes);
4426 #else /* not VMS */
4428 #ifdef DATAGRAM_SOCKETS
4429 /* A datagram is one packet; allow at least 1500+ bytes of data
4430 corresponding to the typical Ethernet frame size. */
4431 if (DATAGRAM_CHAN_P (channel))
4433 /* carryover = 0; */ /* Does carryover make sense for datagrams? */
4434 readmax += 1024;
4436 #endif
4438 chars = (char *) alloca (carryover + readmax);
4439 if (carryover)
4440 /* See the comment above. */
4441 bcopy (SDATA (p->decoding_buf), chars, carryover);
4443 #ifdef DATAGRAM_SOCKETS
4444 /* We have a working select, so proc_buffered_char is always -1. */
4445 if (DATAGRAM_CHAN_P (channel))
4447 int len = datagram_address[channel].len;
4448 nbytes = recvfrom (channel, chars + carryover, readmax - carryover,
4449 0, datagram_address[channel].sa, &len);
4451 else
4452 #endif
4453 if (proc_buffered_char[channel] < 0)
4454 nbytes = emacs_read (channel, chars + carryover, readmax - carryover);
4455 else
4457 chars[carryover] = proc_buffered_char[channel];
4458 proc_buffered_char[channel] = -1;
4459 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1 - carryover);
4460 if (nbytes < 0)
4461 nbytes = 1;
4462 else
4463 nbytes = nbytes + 1;
4465 #endif /* not VMS */
4467 XSETINT (p->decoding_carryover, 0);
4469 /* At this point, NBYTES holds number of bytes just received
4470 (including the one in proc_buffered_char[channel]). */
4471 if (nbytes <= 0)
4473 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
4474 return nbytes;
4475 coding->mode |= CODING_MODE_LAST_BLOCK;
4478 /* Now set NBYTES how many bytes we must decode. */
4479 nbytes += carryover;
4481 /* Read and dispose of the process output. */
4482 outstream = p->filter;
4483 if (!NILP (outstream))
4485 /* We inhibit quit here instead of just catching it so that
4486 hitting ^G when a filter happens to be running won't screw
4487 it up. */
4488 int count = SPECPDL_INDEX ();
4489 Lisp_Object odeactivate;
4490 Lisp_Object obuffer, okeymap;
4491 Lisp_Object text;
4492 int outer_running_asynch_code = running_asynch_code;
4493 int waiting = waiting_for_user_input_p;
4495 /* No need to gcpro these, because all we do with them later
4496 is test them for EQness, and none of them should be a string. */
4497 odeactivate = Vdeactivate_mark;
4498 XSETBUFFER (obuffer, current_buffer);
4499 okeymap = current_buffer->keymap;
4501 specbind (Qinhibit_quit, Qt);
4502 specbind (Qlast_nonmenu_event, Qt);
4504 /* In case we get recursively called,
4505 and we already saved the match data nonrecursively,
4506 save the same match data in safely recursive fashion. */
4507 if (outer_running_asynch_code)
4509 Lisp_Object tem;
4510 /* Don't clobber the CURRENT match data, either! */
4511 tem = Fmatch_data (Qnil, Qnil);
4512 restore_match_data ();
4513 record_unwind_protect (Fset_match_data, Fmatch_data (Qnil, Qnil));
4514 Fset_match_data (tem);
4517 /* For speed, if a search happens within this code,
4518 save the match data in a special nonrecursive fashion. */
4519 running_asynch_code = 1;
4521 text = decode_coding_string (make_unibyte_string (chars, nbytes),
4522 coding, 0);
4523 if (NILP (buffer_defaults.enable_multibyte_characters))
4524 /* We had better return unibyte string. */
4525 text = string_make_unibyte (text);
4527 Vlast_coding_system_used = coding->symbol;
4528 /* A new coding system might be found. */
4529 if (!EQ (p->decode_coding_system, coding->symbol))
4531 p->decode_coding_system = coding->symbol;
4533 /* Don't call setup_coding_system for
4534 proc_decode_coding_system[channel] here. It is done in
4535 detect_coding called via decode_coding above. */
4537 /* If a coding system for encoding is not yet decided, we set
4538 it as the same as coding-system for decoding.
4540 But, before doing that we must check if
4541 proc_encode_coding_system[p->outfd] surely points to a
4542 valid memory because p->outfd will be changed once EOF is
4543 sent to the process. */
4544 if (NILP (p->encode_coding_system)
4545 && proc_encode_coding_system[XINT (p->outfd)])
4547 p->encode_coding_system = coding->symbol;
4548 setup_coding_system (coding->symbol,
4549 proc_encode_coding_system[XINT (p->outfd)]);
4553 carryover = nbytes - coding->consumed;
4554 bcopy (chars + coding->consumed, SDATA (p->decoding_buf),
4555 carryover);
4556 XSETINT (p->decoding_carryover, carryover);
4557 nbytes = SBYTES (text);
4558 nchars = SCHARS (text);
4559 if (nbytes > 0)
4560 internal_condition_case_1 (read_process_output_call,
4561 Fcons (outstream,
4562 Fcons (proc, Fcons (text, Qnil))),
4563 !NILP (Vdebug_on_error) ? Qnil : Qerror,
4564 read_process_output_error_handler);
4566 /* If we saved the match data nonrecursively, restore it now. */
4567 restore_match_data ();
4568 running_asynch_code = outer_running_asynch_code;
4570 /* Handling the process output should not deactivate the mark. */
4571 Vdeactivate_mark = odeactivate;
4573 /* Restore waiting_for_user_input_p as it was
4574 when we were called, in case the filter clobbered it. */
4575 waiting_for_user_input_p = waiting;
4577 #if 0 /* Call record_asynch_buffer_change unconditionally,
4578 because we might have changed minor modes or other things
4579 that affect key bindings. */
4580 if (! EQ (Fcurrent_buffer (), obuffer)
4581 || ! EQ (current_buffer->keymap, okeymap))
4582 #endif
4583 /* But do it only if the caller is actually going to read events.
4584 Otherwise there's no need to make him wake up, and it could
4585 cause trouble (for example it would make Fsit_for return). */
4586 if (waiting_for_user_input_p == -1)
4587 record_asynch_buffer_change ();
4589 #ifdef VMS
4590 start_vms_process_read (vs);
4591 #endif
4592 unbind_to (count, Qnil);
4593 return nchars;
4596 /* If no filter, write into buffer if it isn't dead. */
4597 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
4599 Lisp_Object old_read_only;
4600 int old_begv, old_zv;
4601 int old_begv_byte, old_zv_byte;
4602 Lisp_Object odeactivate;
4603 int before, before_byte;
4604 int opoint_byte;
4605 Lisp_Object text;
4606 struct buffer *b;
4608 odeactivate = Vdeactivate_mark;
4610 Fset_buffer (p->buffer);
4611 opoint = PT;
4612 opoint_byte = PT_BYTE;
4613 old_read_only = current_buffer->read_only;
4614 old_begv = BEGV;
4615 old_zv = ZV;
4616 old_begv_byte = BEGV_BYTE;
4617 old_zv_byte = ZV_BYTE;
4619 current_buffer->read_only = Qnil;
4621 /* Insert new output into buffer
4622 at the current end-of-output marker,
4623 thus preserving logical ordering of input and output. */
4624 if (XMARKER (p->mark)->buffer)
4625 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
4626 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
4627 ZV_BYTE));
4628 else
4629 SET_PT_BOTH (ZV, ZV_BYTE);
4630 before = PT;
4631 before_byte = PT_BYTE;
4633 /* If the output marker is outside of the visible region, save
4634 the restriction and widen. */
4635 if (! (BEGV <= PT && PT <= ZV))
4636 Fwiden ();
4638 text = decode_coding_string (make_unibyte_string (chars, nbytes),
4639 coding, 0);
4640 Vlast_coding_system_used = coding->symbol;
4641 /* A new coding system might be found. See the comment in the
4642 similar code in the previous `if' block. */
4643 if (!EQ (p->decode_coding_system, coding->symbol))
4645 p->decode_coding_system = coding->symbol;
4646 if (NILP (p->encode_coding_system)
4647 && proc_encode_coding_system[XINT (p->outfd)])
4649 p->encode_coding_system = coding->symbol;
4650 setup_coding_system (coding->symbol,
4651 proc_encode_coding_system[XINT (p->outfd)]);
4654 carryover = nbytes - coding->consumed;
4655 bcopy (chars + coding->consumed, SDATA (p->decoding_buf),
4656 carryover);
4657 XSETINT (p->decoding_carryover, carryover);
4658 /* Adjust the multibyteness of TEXT to that of the buffer. */
4659 if (NILP (current_buffer->enable_multibyte_characters)
4660 != ! STRING_MULTIBYTE (text))
4661 text = (STRING_MULTIBYTE (text)
4662 ? Fstring_as_unibyte (text)
4663 : Fstring_as_multibyte (text));
4664 nbytes = SBYTES (text);
4665 nchars = SCHARS (text);
4666 /* Insert before markers in case we are inserting where
4667 the buffer's mark is, and the user's next command is Meta-y. */
4668 insert_from_string_before_markers (text, 0, 0, nchars, nbytes, 0);
4670 /* Make sure the process marker's position is valid when the
4671 process buffer is changed in the signal_after_change above.
4672 W3 is known to do that. */
4673 if (BUFFERP (p->buffer)
4674 && (b = XBUFFER (p->buffer), b != current_buffer))
4675 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
4676 else
4677 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
4679 update_mode_lines++;
4681 /* Make sure opoint and the old restrictions
4682 float ahead of any new text just as point would. */
4683 if (opoint >= before)
4685 opoint += PT - before;
4686 opoint_byte += PT_BYTE - before_byte;
4688 if (old_begv > before)
4690 old_begv += PT - before;
4691 old_begv_byte += PT_BYTE - before_byte;
4693 if (old_zv >= before)
4695 old_zv += PT - before;
4696 old_zv_byte += PT_BYTE - before_byte;
4699 /* If the restriction isn't what it should be, set it. */
4700 if (old_begv != BEGV || old_zv != ZV)
4701 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
4703 /* Handling the process output should not deactivate the mark. */
4704 Vdeactivate_mark = odeactivate;
4706 current_buffer->read_only = old_read_only;
4707 SET_PT_BOTH (opoint, opoint_byte);
4708 set_buffer_internal (old);
4710 #ifdef VMS
4711 start_vms_process_read (vs);
4712 #endif
4713 return nbytes;
4716 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
4717 0, 0, 0,
4718 doc: /* Returns non-nil if emacs is waiting for input from the user.
4719 This is intended for use by asynchronous process output filters and sentinels. */)
4722 return (waiting_for_user_input_p ? Qt : Qnil);
4725 /* Sending data to subprocess */
4727 jmp_buf send_process_frame;
4728 Lisp_Object process_sent_to;
4730 SIGTYPE
4731 send_process_trap ()
4733 #ifdef BSD4_1
4734 sigrelse (SIGPIPE);
4735 sigrelse (SIGALRM);
4736 #endif /* BSD4_1 */
4737 longjmp (send_process_frame, 1);
4740 /* Send some data to process PROC.
4741 BUF is the beginning of the data; LEN is the number of characters.
4742 OBJECT is the Lisp object that the data comes from. If OBJECT is
4743 nil or t, it means that the data comes from C string.
4745 If OBJECT is not nil, the data is encoded by PROC's coding-system
4746 for encoding before it is sent.
4748 This function can evaluate Lisp code and can garbage collect. */
4750 void
4751 send_process (proc, buf, len, object)
4752 volatile Lisp_Object proc;
4753 unsigned char *volatile buf;
4754 volatile int len;
4755 volatile Lisp_Object object;
4757 /* Use volatile to protect variables from being clobbered by longjmp. */
4758 int rv;
4759 struct coding_system *coding;
4760 struct gcpro gcpro1;
4762 GCPRO1 (object);
4764 #ifdef VMS
4765 struct Lisp_Process *p = XPROCESS (proc);
4766 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
4767 #endif /* VMS */
4769 if (! NILP (XPROCESS (proc)->raw_status_low))
4770 update_status (XPROCESS (proc));
4771 if (! EQ (XPROCESS (proc)->status, Qrun))
4772 error ("Process %s not running",
4773 SDATA (XPROCESS (proc)->name));
4774 if (XINT (XPROCESS (proc)->outfd) < 0)
4775 error ("Output file descriptor of %s is closed",
4776 SDATA (XPROCESS (proc)->name));
4778 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
4779 Vlast_coding_system_used = coding->symbol;
4781 if ((STRINGP (object) && STRING_MULTIBYTE (object))
4782 || (BUFFERP (object)
4783 && !NILP (XBUFFER (object)->enable_multibyte_characters))
4784 || EQ (object, Qt))
4786 if (!EQ (coding->symbol, XPROCESS (proc)->encode_coding_system))
4787 /* The coding system for encoding was changed to raw-text
4788 because we sent a unibyte text previously. Now we are
4789 sending a multibyte text, thus we must encode it by the
4790 original coding system specified for the current
4791 process. */
4792 setup_coding_system (XPROCESS (proc)->encode_coding_system, coding);
4793 /* src_multibyte should be set to 1 _after_ a call to
4794 setup_coding_system, since it resets src_multibyte to
4795 zero. */
4796 coding->src_multibyte = 1;
4798 else
4800 /* For sending a unibyte text, character code conversion should
4801 not take place but EOL conversion should. So, setup raw-text
4802 or one of the subsidiary if we have not yet done it. */
4803 if (coding->type != coding_type_raw_text)
4805 if (CODING_REQUIRE_FLUSHING (coding))
4807 /* But, before changing the coding, we must flush out data. */
4808 coding->mode |= CODING_MODE_LAST_BLOCK;
4809 send_process (proc, "", 0, Qt);
4811 coding->src_multibyte = 0;
4812 setup_raw_text_coding_system (coding);
4815 coding->dst_multibyte = 0;
4817 if (CODING_REQUIRE_ENCODING (coding))
4819 int require = encoding_buffer_size (coding, len);
4820 int from_byte = -1, from = -1, to = -1;
4821 unsigned char *temp_buf = NULL;
4823 if (BUFFERP (object))
4825 from_byte = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
4826 from = buf_bytepos_to_charpos (XBUFFER (object), from_byte);
4827 to = buf_bytepos_to_charpos (XBUFFER (object), from_byte + len);
4829 else if (STRINGP (object))
4831 from_byte = buf - SDATA (object);
4832 from = string_byte_to_char (object, from_byte);
4833 to = string_byte_to_char (object, from_byte + len);
4836 if (coding->composing != COMPOSITION_DISABLED)
4838 if (from_byte >= 0)
4839 coding_save_composition (coding, from, to, object);
4840 else
4841 coding->composing = COMPOSITION_DISABLED;
4844 if (SBYTES (XPROCESS (proc)->encoding_buf) < require)
4845 XPROCESS (proc)->encoding_buf = make_uninit_string (require);
4847 if (from_byte >= 0)
4848 buf = (BUFFERP (object)
4849 ? BUF_BYTE_ADDRESS (XBUFFER (object), from_byte)
4850 : SDATA (object) + from_byte);
4852 object = XPROCESS (proc)->encoding_buf;
4853 encode_coding (coding, (char *) buf, SDATA (object),
4854 len, SBYTES (object));
4855 len = coding->produced;
4856 buf = SDATA (object);
4857 if (temp_buf)
4858 xfree (temp_buf);
4861 #ifdef VMS
4862 vs = get_vms_process_pointer (p->pid);
4863 if (vs == 0)
4864 error ("Could not find this process: %x", p->pid);
4865 else if (write_to_vms_process (vs, buf, len))
4867 #else /* not VMS */
4869 if (pty_max_bytes == 0)
4871 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
4872 pty_max_bytes = fpathconf (XFASTINT (XPROCESS (proc)->outfd),
4873 _PC_MAX_CANON);
4874 if (pty_max_bytes < 0)
4875 pty_max_bytes = 250;
4876 #else
4877 pty_max_bytes = 250;
4878 #endif
4879 /* Deduct one, to leave space for the eof. */
4880 pty_max_bytes--;
4883 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
4884 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
4885 when returning with longjmp despite being declared volatile. */
4886 if (!setjmp (send_process_frame))
4888 process_sent_to = proc;
4889 while (len > 0)
4891 int this = len;
4892 SIGTYPE (*old_sigpipe)();
4894 /* Decide how much data we can send in one batch.
4895 Long lines need to be split into multiple batches. */
4896 if (!NILP (XPROCESS (proc)->pty_flag))
4898 /* Starting this at zero is always correct when not the first
4899 iteration because the previous iteration ended by sending C-d.
4900 It may not be correct for the first iteration
4901 if a partial line was sent in a separate send_process call.
4902 If that proves worth handling, we need to save linepos
4903 in the process object. */
4904 int linepos = 0;
4905 unsigned char *ptr = (unsigned char *) buf;
4906 unsigned char *end = (unsigned char *) buf + len;
4908 /* Scan through this text for a line that is too long. */
4909 while (ptr != end && linepos < pty_max_bytes)
4911 if (*ptr == '\n')
4912 linepos = 0;
4913 else
4914 linepos++;
4915 ptr++;
4917 /* If we found one, break the line there
4918 and put in a C-d to force the buffer through. */
4919 this = ptr - buf;
4922 /* Send this batch, using one or more write calls. */
4923 while (this > 0)
4925 int outfd = XINT (XPROCESS (proc)->outfd);
4926 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
4927 #ifdef DATAGRAM_SOCKETS
4928 if (DATAGRAM_CHAN_P (outfd))
4930 rv = sendto (outfd, (char *) buf, this,
4931 0, datagram_address[outfd].sa,
4932 datagram_address[outfd].len);
4933 if (rv < 0 && errno == EMSGSIZE)
4934 report_file_error ("sending datagram", Fcons (proc, Qnil));
4936 else
4937 #endif
4938 rv = emacs_write (outfd, (char *) buf, this);
4939 signal (SIGPIPE, old_sigpipe);
4941 if (rv < 0)
4943 if (0
4944 #ifdef EWOULDBLOCK
4945 || errno == EWOULDBLOCK
4946 #endif
4947 #ifdef EAGAIN
4948 || errno == EAGAIN
4949 #endif
4951 /* Buffer is full. Wait, accepting input;
4952 that may allow the program
4953 to finish doing output and read more. */
4955 Lisp_Object zero;
4956 int offset = 0;
4958 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
4959 /* A gross hack to work around a bug in FreeBSD.
4960 In the following sequence, read(2) returns
4961 bogus data:
4963 write(2) 1022 bytes
4964 write(2) 954 bytes, get EAGAIN
4965 read(2) 1024 bytes in process_read_output
4966 read(2) 11 bytes in process_read_output
4968 That is, read(2) returns more bytes than have
4969 ever been written successfully. The 1033 bytes
4970 read are the 1022 bytes written successfully
4971 after processing (for example with CRs added if
4972 the terminal is set up that way which it is
4973 here). The same bytes will be seen again in a
4974 later read(2), without the CRs. */
4976 if (errno == EAGAIN)
4978 int flags = FWRITE;
4979 ioctl (XINT (XPROCESS (proc)->outfd), TIOCFLUSH,
4980 &flags);
4982 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
4984 /* Running filters might relocate buffers or strings.
4985 Arrange to relocate BUF. */
4986 if (BUFFERP (object))
4987 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
4988 else if (STRINGP (object))
4989 offset = buf - SDATA (object);
4991 XSETFASTINT (zero, 0);
4992 #ifdef EMACS_HAS_USECS
4993 wait_reading_process_input (0, 20000, zero, 0);
4994 #else
4995 wait_reading_process_input (1, 0, zero, 0);
4996 #endif
4998 if (BUFFERP (object))
4999 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5000 else if (STRINGP (object))
5001 buf = offset + SDATA (object);
5003 rv = 0;
5005 else
5006 /* This is a real error. */
5007 report_file_error ("writing to process", Fcons (proc, Qnil));
5009 buf += rv;
5010 len -= rv;
5011 this -= rv;
5014 /* If we sent just part of the string, put in an EOF
5015 to force it through, before we send the rest. */
5016 if (len > 0)
5017 Fprocess_send_eof (proc);
5020 #endif /* not VMS */
5021 else
5023 #ifndef VMS
5024 proc = process_sent_to;
5025 #endif
5026 XPROCESS (proc)->raw_status_low = Qnil;
5027 XPROCESS (proc)->raw_status_high = Qnil;
5028 XPROCESS (proc)->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5029 XSETINT (XPROCESS (proc)->tick, ++process_tick);
5030 deactivate_process (proc);
5031 #ifdef VMS
5032 error ("Error writing to process %s; closed it",
5033 SDATA (XPROCESS (proc)->name));
5034 #else
5035 error ("SIGPIPE raised on process %s; closed it",
5036 SDATA (XPROCESS (proc)->name));
5037 #endif
5040 UNGCPRO;
5043 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5044 3, 3, 0,
5045 doc: /* Send current contents of region as input to PROCESS.
5046 PROCESS may be a process, a buffer, the name of a process or buffer, or
5047 nil, indicating the current buffer's process.
5048 Called from program, takes three arguments, PROCESS, START and END.
5049 If the region is more than 500 characters long,
5050 it is sent in several bunches. This may happen even for shorter regions.
5051 Output from processes can arrive in between bunches. */)
5052 (process, start, end)
5053 Lisp_Object process, start, end;
5055 Lisp_Object proc;
5056 int start1, end1;
5058 proc = get_process (process);
5059 validate_region (&start, &end);
5061 if (XINT (start) < GPT && XINT (end) > GPT)
5062 move_gap (XINT (start));
5064 start1 = CHAR_TO_BYTE (XINT (start));
5065 end1 = CHAR_TO_BYTE (XINT (end));
5066 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5067 Fcurrent_buffer ());
5069 return Qnil;
5072 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5073 2, 2, 0,
5074 doc: /* Send PROCESS the contents of STRING as input.
5075 PROCESS may be a process, a buffer, the name of a process or buffer, or
5076 nil, indicating the current buffer's process.
5077 If STRING is more than 500 characters long,
5078 it is sent in several bunches. This may happen even for shorter strings.
5079 Output from processes can arrive in between bunches. */)
5080 (process, string)
5081 Lisp_Object process, string;
5083 Lisp_Object proc;
5084 CHECK_STRING (string);
5085 proc = get_process (process);
5086 send_process (proc, SDATA (string),
5087 SBYTES (string), string);
5088 return Qnil;
5091 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5092 Sprocess_running_child_p, 0, 1, 0,
5093 doc: /* Return t if PROCESS has given the terminal to a child.
5094 If the operating system does not make it possible to find out,
5095 return t unconditionally. */)
5096 (process)
5097 Lisp_Object process;
5099 /* Initialize in case ioctl doesn't exist or gives an error,
5100 in a way that will cause returning t. */
5101 int gid = 0;
5102 Lisp_Object proc;
5103 struct Lisp_Process *p;
5105 proc = get_process (process);
5106 p = XPROCESS (proc);
5108 if (!EQ (p->childp, Qt))
5109 error ("Process %s is not a subprocess",
5110 SDATA (p->name));
5111 if (XINT (p->infd) < 0)
5112 error ("Process %s is not active",
5113 SDATA (p->name));
5115 #ifdef TIOCGPGRP
5116 if (!NILP (p->subtty))
5117 ioctl (XFASTINT (p->subtty), TIOCGPGRP, &gid);
5118 else
5119 ioctl (XINT (p->infd), TIOCGPGRP, &gid);
5120 #endif /* defined (TIOCGPGRP ) */
5122 if (gid == XFASTINT (p->pid))
5123 return Qnil;
5124 return Qt;
5127 /* send a signal number SIGNO to PROCESS.
5128 If CURRENT_GROUP is t, that means send to the process group
5129 that currently owns the terminal being used to communicate with PROCESS.
5130 This is used for various commands in shell mode.
5131 If CURRENT_GROUP is lambda, that means send to the process group
5132 that currently owns the terminal, but only if it is NOT the shell itself.
5134 If NOMSG is zero, insert signal-announcements into process's buffers
5135 right away.
5137 If we can, we try to signal PROCESS by sending control characters
5138 down the pty. This allows us to signal inferiors who have changed
5139 their uid, for which killpg would return an EPERM error. */
5141 static void
5142 process_send_signal (process, signo, current_group, nomsg)
5143 Lisp_Object process;
5144 int signo;
5145 Lisp_Object current_group;
5146 int nomsg;
5148 Lisp_Object proc;
5149 register struct Lisp_Process *p;
5150 int gid;
5151 int no_pgrp = 0;
5153 proc = get_process (process);
5154 p = XPROCESS (proc);
5156 if (!EQ (p->childp, Qt))
5157 error ("Process %s is not a subprocess",
5158 SDATA (p->name));
5159 if (XINT (p->infd) < 0)
5160 error ("Process %s is not active",
5161 SDATA (p->name));
5163 if (NILP (p->pty_flag))
5164 current_group = Qnil;
5166 /* If we are using pgrps, get a pgrp number and make it negative. */
5167 if (NILP (current_group))
5168 /* Send the signal to the shell's process group. */
5169 gid = XFASTINT (p->pid);
5170 else
5172 #ifdef SIGNALS_VIA_CHARACTERS
5173 /* If possible, send signals to the entire pgrp
5174 by sending an input character to it. */
5176 /* TERMIOS is the latest and bestest, and seems most likely to
5177 work. If the system has it, use it. */
5178 #ifdef HAVE_TERMIOS
5179 struct termios t;
5181 switch (signo)
5183 case SIGINT:
5184 tcgetattr (XINT (p->infd), &t);
5185 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5186 return;
5188 case SIGQUIT:
5189 tcgetattr (XINT (p->infd), &t);
5190 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5191 return;
5193 case SIGTSTP:
5194 tcgetattr (XINT (p->infd), &t);
5195 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5196 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5197 #else
5198 send_process (proc, &t.c_cc[VSUSP], 1, Qnil);
5199 #endif
5200 return;
5203 #else /* ! HAVE_TERMIOS */
5205 /* On Berkeley descendants, the following IOCTL's retrieve the
5206 current control characters. */
5207 #if defined (TIOCGLTC) && defined (TIOCGETC)
5209 struct tchars c;
5210 struct ltchars lc;
5212 switch (signo)
5214 case SIGINT:
5215 ioctl (XINT (p->infd), TIOCGETC, &c);
5216 send_process (proc, &c.t_intrc, 1, Qnil);
5217 return;
5218 case SIGQUIT:
5219 ioctl (XINT (p->infd), TIOCGETC, &c);
5220 send_process (proc, &c.t_quitc, 1, Qnil);
5221 return;
5222 #ifdef SIGTSTP
5223 case SIGTSTP:
5224 ioctl (XINT (p->infd), TIOCGLTC, &lc);
5225 send_process (proc, &lc.t_suspc, 1, Qnil);
5226 return;
5227 #endif /* ! defined (SIGTSTP) */
5230 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5232 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
5233 characters. */
5234 #ifdef TCGETA
5235 struct termio t;
5236 switch (signo)
5238 case SIGINT:
5239 ioctl (XINT (p->infd), TCGETA, &t);
5240 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5241 return;
5242 case SIGQUIT:
5243 ioctl (XINT (p->infd), TCGETA, &t);
5244 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5245 return;
5246 #ifdef SIGTSTP
5247 case SIGTSTP:
5248 ioctl (XINT (p->infd), TCGETA, &t);
5249 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5250 return;
5251 #endif /* ! defined (SIGTSTP) */
5253 #else /* ! defined (TCGETA) */
5254 Your configuration files are messed up.
5255 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
5256 you'd better be using one of the alternatives above! */
5257 #endif /* ! defined (TCGETA) */
5258 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5259 #endif /* ! defined HAVE_TERMIOS */
5260 abort ();
5261 /* The code above always returns from the function. */
5262 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5264 #ifdef TIOCGPGRP
5265 /* Get the current pgrp using the tty itself, if we have that.
5266 Otherwise, use the pty to get the pgrp.
5267 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5268 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5269 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5270 His patch indicates that if TIOCGPGRP returns an error, then
5271 we should just assume that p->pid is also the process group id. */
5273 int err;
5275 if (!NILP (p->subtty))
5276 err = ioctl (XFASTINT (p->subtty), TIOCGPGRP, &gid);
5277 else
5278 err = ioctl (XINT (p->infd), TIOCGPGRP, &gid);
5280 if (err == -1)
5281 /* If we can't get the information, assume
5282 the shell owns the tty. */
5283 gid = XFASTINT (p->pid);
5286 /* It is not clear whether anything really can set GID to -1.
5287 Perhaps on some system one of those ioctls can or could do so.
5288 Or perhaps this is vestigial. */
5289 if (gid == -1)
5290 no_pgrp = 1;
5291 #else /* ! defined (TIOCGPGRP ) */
5292 /* Can't select pgrps on this system, so we know that
5293 the child itself heads the pgrp. */
5294 gid = XFASTINT (p->pid);
5295 #endif /* ! defined (TIOCGPGRP ) */
5297 /* If current_group is lambda, and the shell owns the terminal,
5298 don't send any signal. */
5299 if (EQ (current_group, Qlambda) && gid == XFASTINT (p->pid))
5300 return;
5303 switch (signo)
5305 #ifdef SIGCONT
5306 case SIGCONT:
5307 p->raw_status_low = Qnil;
5308 p->raw_status_high = Qnil;
5309 p->status = Qrun;
5310 XSETINT (p->tick, ++process_tick);
5311 if (!nomsg)
5312 status_notify ();
5313 break;
5314 #endif /* ! defined (SIGCONT) */
5315 case SIGINT:
5316 #ifdef VMS
5317 send_process (proc, "\003", 1, Qnil); /* ^C */
5318 goto whoosh;
5319 #endif
5320 case SIGQUIT:
5321 #ifdef VMS
5322 send_process (proc, "\031", 1, Qnil); /* ^Y */
5323 goto whoosh;
5324 #endif
5325 case SIGKILL:
5326 #ifdef VMS
5327 sys$forcex (&(XFASTINT (p->pid)), 0, 1);
5328 whoosh:
5329 #endif
5330 flush_pending_output (XINT (p->infd));
5331 break;
5334 /* If we don't have process groups, send the signal to the immediate
5335 subprocess. That isn't really right, but it's better than any
5336 obvious alternative. */
5337 if (no_pgrp)
5339 kill (XFASTINT (p->pid), signo);
5340 return;
5343 /* gid may be a pid, or minus a pgrp's number */
5344 #ifdef TIOCSIGSEND
5345 if (!NILP (current_group))
5346 ioctl (XINT (p->infd), TIOCSIGSEND, signo);
5347 else
5349 gid = - XFASTINT (p->pid);
5350 kill (gid, signo);
5352 #else /* ! defined (TIOCSIGSEND) */
5353 EMACS_KILLPG (gid, signo);
5354 #endif /* ! defined (TIOCSIGSEND) */
5357 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
5358 doc: /* Interrupt process PROCESS.
5359 PROCESS may be a process, a buffer, or the name of a process or buffer.
5360 nil or no arg means current buffer's process.
5361 Second arg CURRENT-GROUP non-nil means send signal to
5362 the current process-group of the process's controlling terminal
5363 rather than to the process's own process group.
5364 If the process is a shell, this means interrupt current subjob
5365 rather than the shell.
5367 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
5368 don't send the signal. */)
5369 (process, current_group)
5370 Lisp_Object process, current_group;
5372 process_send_signal (process, SIGINT, current_group, 0);
5373 return process;
5376 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
5377 doc: /* Kill process PROCESS. May be process or name of one.
5378 See function `interrupt-process' for more details on usage. */)
5379 (process, current_group)
5380 Lisp_Object process, current_group;
5382 process_send_signal (process, SIGKILL, current_group, 0);
5383 return process;
5386 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
5387 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
5388 See function `interrupt-process' for more details on usage. */)
5389 (process, current_group)
5390 Lisp_Object process, current_group;
5392 process_send_signal (process, SIGQUIT, current_group, 0);
5393 return process;
5396 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
5397 doc: /* Stop process PROCESS. May be process or name of one.
5398 See function `interrupt-process' for more details on usage.
5399 If PROCESS is a network process, inhibit handling of incoming traffic. */)
5400 (process, current_group)
5401 Lisp_Object process, current_group;
5403 #ifdef HAVE_SOCKETS
5404 if (PROCESSP (process) && NETCONN_P (process))
5406 struct Lisp_Process *p;
5408 p = XPROCESS (process);
5409 if (NILP (p->command)
5410 && XINT (p->infd) >= 0)
5412 FD_CLR (XINT (p->infd), &input_wait_mask);
5413 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
5415 p->command = Qt;
5416 return process;
5418 #endif
5419 #ifndef SIGTSTP
5420 error ("no SIGTSTP support");
5421 #else
5422 process_send_signal (process, SIGTSTP, current_group, 0);
5423 #endif
5424 return process;
5427 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
5428 doc: /* Continue process PROCESS. May be process or name of one.
5429 See function `interrupt-process' for more details on usage.
5430 If PROCESS is a network process, resume handling of incoming traffic. */)
5431 (process, current_group)
5432 Lisp_Object process, current_group;
5434 #ifdef HAVE_SOCKETS
5435 if (PROCESSP (process) && NETCONN_P (process))
5437 struct Lisp_Process *p;
5439 p = XPROCESS (process);
5440 if (EQ (p->command, Qt)
5441 && XINT (p->infd) >= 0
5442 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
5444 FD_SET (XINT (p->infd), &input_wait_mask);
5445 FD_SET (XINT (p->infd), &non_keyboard_wait_mask);
5447 p->command = Qnil;
5448 return process;
5450 #endif
5451 #ifdef SIGCONT
5452 process_send_signal (process, SIGCONT, current_group, 0);
5453 #else
5454 error ("no SIGCONT support");
5455 #endif
5456 return process;
5459 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
5460 2, 2, "sProcess (name or number): \nnSignal code: ",
5461 doc: /* Send PROCESS the signal with code SIGCODE.
5462 PROCESS may also be an integer specifying the process id of the
5463 process to signal; in this case, the process need not be a child of
5464 this Emacs.
5465 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
5466 (process, sigcode)
5467 Lisp_Object process, sigcode;
5469 Lisp_Object pid;
5471 if (INTEGERP (process))
5473 pid = process;
5474 goto got_it;
5477 if (STRINGP (process))
5479 Lisp_Object tem;
5480 if (tem = Fget_process (process), NILP (tem))
5482 pid = Fstring_to_number (process, make_number (10));
5483 if (XINT (pid) != 0)
5484 goto got_it;
5486 process = tem;
5488 else
5489 process = get_process (process);
5491 if (NILP (process))
5492 return process;
5494 CHECK_PROCESS (process);
5495 pid = XPROCESS (process)->pid;
5496 if (!INTEGERP (pid) || XINT (pid) <= 0)
5497 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
5499 got_it:
5501 #define handle_signal(NAME, VALUE) \
5502 else if (!strcmp (name, NAME)) \
5503 XSETINT (sigcode, VALUE)
5505 if (INTEGERP (sigcode))
5507 else
5509 unsigned char *name;
5511 CHECK_SYMBOL (sigcode);
5512 name = SDATA (SYMBOL_NAME (sigcode));
5514 if (0)
5516 #ifdef SIGHUP
5517 handle_signal ("SIGHUP", SIGHUP);
5518 #endif
5519 #ifdef SIGINT
5520 handle_signal ("SIGINT", SIGINT);
5521 #endif
5522 #ifdef SIGQUIT
5523 handle_signal ("SIGQUIT", SIGQUIT);
5524 #endif
5525 #ifdef SIGILL
5526 handle_signal ("SIGILL", SIGILL);
5527 #endif
5528 #ifdef SIGABRT
5529 handle_signal ("SIGABRT", SIGABRT);
5530 #endif
5531 #ifdef SIGEMT
5532 handle_signal ("SIGEMT", SIGEMT);
5533 #endif
5534 #ifdef SIGKILL
5535 handle_signal ("SIGKILL", SIGKILL);
5536 #endif
5537 #ifdef SIGFPE
5538 handle_signal ("SIGFPE", SIGFPE);
5539 #endif
5540 #ifdef SIGBUS
5541 handle_signal ("SIGBUS", SIGBUS);
5542 #endif
5543 #ifdef SIGSEGV
5544 handle_signal ("SIGSEGV", SIGSEGV);
5545 #endif
5546 #ifdef SIGSYS
5547 handle_signal ("SIGSYS", SIGSYS);
5548 #endif
5549 #ifdef SIGPIPE
5550 handle_signal ("SIGPIPE", SIGPIPE);
5551 #endif
5552 #ifdef SIGALRM
5553 handle_signal ("SIGALRM", SIGALRM);
5554 #endif
5555 #ifdef SIGTERM
5556 handle_signal ("SIGTERM", SIGTERM);
5557 #endif
5558 #ifdef SIGURG
5559 handle_signal ("SIGURG", SIGURG);
5560 #endif
5561 #ifdef SIGSTOP
5562 handle_signal ("SIGSTOP", SIGSTOP);
5563 #endif
5564 #ifdef SIGTSTP
5565 handle_signal ("SIGTSTP", SIGTSTP);
5566 #endif
5567 #ifdef SIGCONT
5568 handle_signal ("SIGCONT", SIGCONT);
5569 #endif
5570 #ifdef SIGCHLD
5571 handle_signal ("SIGCHLD", SIGCHLD);
5572 #endif
5573 #ifdef SIGTTIN
5574 handle_signal ("SIGTTIN", SIGTTIN);
5575 #endif
5576 #ifdef SIGTTOU
5577 handle_signal ("SIGTTOU", SIGTTOU);
5578 #endif
5579 #ifdef SIGIO
5580 handle_signal ("SIGIO", SIGIO);
5581 #endif
5582 #ifdef SIGXCPU
5583 handle_signal ("SIGXCPU", SIGXCPU);
5584 #endif
5585 #ifdef SIGXFSZ
5586 handle_signal ("SIGXFSZ", SIGXFSZ);
5587 #endif
5588 #ifdef SIGVTALRM
5589 handle_signal ("SIGVTALRM", SIGVTALRM);
5590 #endif
5591 #ifdef SIGPROF
5592 handle_signal ("SIGPROF", SIGPROF);
5593 #endif
5594 #ifdef SIGWINCH
5595 handle_signal ("SIGWINCH", SIGWINCH);
5596 #endif
5597 #ifdef SIGINFO
5598 handle_signal ("SIGINFO", SIGINFO);
5599 #endif
5600 #ifdef SIGUSR1
5601 handle_signal ("SIGUSR1", SIGUSR1);
5602 #endif
5603 #ifdef SIGUSR2
5604 handle_signal ("SIGUSR2", SIGUSR2);
5605 #endif
5606 else
5607 error ("Undefined signal name %s", name);
5610 #undef handle_signal
5612 return make_number (kill (XINT (pid), XINT (sigcode)));
5615 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
5616 doc: /* Make PROCESS see end-of-file in its input.
5617 EOF comes after any text already sent to it.
5618 PROCESS may be a process, a buffer, the name of a process or buffer, or
5619 nil, indicating the current buffer's process.
5620 If PROCESS is a network connection, or is a process communicating
5621 through a pipe (as opposed to a pty), then you cannot send any more
5622 text to PROCESS after you call this function. */)
5623 (process)
5624 Lisp_Object process;
5626 Lisp_Object proc;
5627 struct coding_system *coding;
5629 if (DATAGRAM_CONN_P (process))
5630 return process;
5632 proc = get_process (process);
5633 coding = proc_encode_coding_system[XINT (XPROCESS (proc)->outfd)];
5635 /* Make sure the process is really alive. */
5636 if (! NILP (XPROCESS (proc)->raw_status_low))
5637 update_status (XPROCESS (proc));
5638 if (! EQ (XPROCESS (proc)->status, Qrun))
5639 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
5641 if (CODING_REQUIRE_FLUSHING (coding))
5643 coding->mode |= CODING_MODE_LAST_BLOCK;
5644 send_process (proc, "", 0, Qnil);
5647 #ifdef VMS
5648 send_process (proc, "\032", 1, Qnil); /* ^z */
5649 #else
5650 if (!NILP (XPROCESS (proc)->pty_flag))
5651 send_process (proc, "\004", 1, Qnil);
5652 else
5654 int old_outfd, new_outfd;
5656 #ifdef HAVE_SHUTDOWN
5657 /* If this is a network connection, or socketpair is used
5658 for communication with the subprocess, call shutdown to cause EOF.
5659 (In some old system, shutdown to socketpair doesn't work.
5660 Then we just can't win.) */
5661 if (NILP (XPROCESS (proc)->pid)
5662 || XINT (XPROCESS (proc)->outfd) == XINT (XPROCESS (proc)->infd))
5663 shutdown (XINT (XPROCESS (proc)->outfd), 1);
5664 /* In case of socketpair, outfd == infd, so don't close it. */
5665 if (XINT (XPROCESS (proc)->outfd) != XINT (XPROCESS (proc)->infd))
5666 emacs_close (XINT (XPROCESS (proc)->outfd));
5667 #else /* not HAVE_SHUTDOWN */
5668 emacs_close (XINT (XPROCESS (proc)->outfd));
5669 #endif /* not HAVE_SHUTDOWN */
5670 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
5671 old_outfd = XINT (XPROCESS (proc)->outfd);
5673 if (!proc_encode_coding_system[new_outfd])
5674 proc_encode_coding_system[new_outfd]
5675 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
5676 bcopy (proc_encode_coding_system[old_outfd],
5677 proc_encode_coding_system[new_outfd],
5678 sizeof (struct coding_system));
5679 bzero (proc_encode_coding_system[old_outfd],
5680 sizeof (struct coding_system));
5682 XSETINT (XPROCESS (proc)->outfd, new_outfd);
5684 #endif /* VMS */
5685 return process;
5688 /* Kill all processes associated with `buffer'.
5689 If `buffer' is nil, kill all processes */
5691 void
5692 kill_buffer_processes (buffer)
5693 Lisp_Object buffer;
5695 Lisp_Object tail, proc;
5697 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
5699 proc = XCDR (XCAR (tail));
5700 if (GC_PROCESSP (proc)
5701 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
5703 if (NETCONN_P (proc))
5704 Fdelete_process (proc);
5705 else if (XINT (XPROCESS (proc)->infd) >= 0)
5706 process_send_signal (proc, SIGHUP, Qnil, 1);
5711 /* On receipt of a signal that a child status has changed, loop asking
5712 about children with changed statuses until the system says there
5713 are no more.
5715 All we do is change the status; we do not run sentinels or print
5716 notifications. That is saved for the next time keyboard input is
5717 done, in order to avoid timing errors.
5719 ** WARNING: this can be called during garbage collection.
5720 Therefore, it must not be fooled by the presence of mark bits in
5721 Lisp objects.
5723 ** USG WARNING: Although it is not obvious from the documentation
5724 in signal(2), on a USG system the SIGCLD handler MUST NOT call
5725 signal() before executing at least one wait(), otherwise the
5726 handler will be called again, resulting in an infinite loop. The
5727 relevant portion of the documentation reads "SIGCLD signals will be
5728 queued and the signal-catching function will be continually
5729 reentered until the queue is empty". Invoking signal() causes the
5730 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
5731 Inc. */
5733 SIGTYPE
5734 sigchld_handler (signo)
5735 int signo;
5737 int old_errno = errno;
5738 Lisp_Object proc;
5739 register struct Lisp_Process *p;
5740 extern EMACS_TIME *input_available_clear_time;
5742 #ifdef BSD4_1
5743 extern int sigheld;
5744 sigheld |= sigbit (SIGCHLD);
5745 #endif
5747 while (1)
5749 register int pid;
5750 WAITTYPE w;
5751 Lisp_Object tail;
5753 #ifdef WNOHANG
5754 #ifndef WUNTRACED
5755 #define WUNTRACED 0
5756 #endif /* no WUNTRACED */
5757 /* Keep trying to get a status until we get a definitive result. */
5760 errno = 0;
5761 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
5763 while (pid < 0 && errno == EINTR);
5765 if (pid <= 0)
5767 /* PID == 0 means no processes found, PID == -1 means a real
5768 failure. We have done all our job, so return. */
5770 /* USG systems forget handlers when they are used;
5771 must reestablish each time */
5772 #if defined (USG) && !defined (POSIX_SIGNALS)
5773 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
5774 #endif
5775 #ifdef BSD4_1
5776 sigheld &= ~sigbit (SIGCHLD);
5777 sigrelse (SIGCHLD);
5778 #endif
5779 errno = old_errno;
5780 return;
5782 #else
5783 pid = wait (&w);
5784 #endif /* no WNOHANG */
5786 /* Find the process that signaled us, and record its status. */
5788 p = 0;
5789 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
5791 proc = XCDR (XCAR (tail));
5792 p = XPROCESS (proc);
5793 if (GC_EQ (p->childp, Qt) && XINT (p->pid) == pid)
5794 break;
5795 p = 0;
5798 /* Look for an asynchronous process whose pid hasn't been filled
5799 in yet. */
5800 if (p == 0)
5801 for (tail = Vprocess_alist; GC_CONSP (tail); tail = XCDR (tail))
5803 proc = XCDR (XCAR (tail));
5804 p = XPROCESS (proc);
5805 if (GC_INTEGERP (p->pid) && XINT (p->pid) == -1)
5806 break;
5807 p = 0;
5810 /* Change the status of the process that was found. */
5811 if (p != 0)
5813 union { int i; WAITTYPE wt; } u;
5814 int clear_desc_flag = 0;
5816 XSETINT (p->tick, ++process_tick);
5817 u.wt = w;
5818 XSETINT (p->raw_status_low, u.i & 0xffff);
5819 XSETINT (p->raw_status_high, u.i >> 16);
5821 /* If process has terminated, stop waiting for its output. */
5822 if ((WIFSIGNALED (w) || WIFEXITED (w))
5823 && XINT (p->infd) >= 0)
5824 clear_desc_flag = 1;
5826 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
5827 if (clear_desc_flag)
5829 FD_CLR (XINT (p->infd), &input_wait_mask);
5830 FD_CLR (XINT (p->infd), &non_keyboard_wait_mask);
5833 /* Tell wait_reading_process_input that it needs to wake up and
5834 look around. */
5835 if (input_available_clear_time)
5836 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
5839 /* There was no asynchronous process found for that id. Check
5840 if we have a synchronous process. */
5841 else
5843 synch_process_alive = 0;
5845 /* Report the status of the synchronous process. */
5846 if (WIFEXITED (w))
5847 synch_process_retcode = WRETCODE (w);
5848 else if (WIFSIGNALED (w))
5850 int code = WTERMSIG (w);
5851 char *signame;
5853 synchronize_system_messages_locale ();
5854 signame = strsignal (code);
5856 if (signame == 0)
5857 signame = "unknown";
5859 synch_process_death = signame;
5862 /* Tell wait_reading_process_input that it needs to wake up and
5863 look around. */
5864 if (input_available_clear_time)
5865 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
5868 /* On some systems, we must return right away.
5869 If any more processes want to signal us, we will
5870 get another signal.
5871 Otherwise (on systems that have WNOHANG), loop around
5872 to use up all the processes that have something to tell us. */
5873 #if (defined WINDOWSNT \
5874 || (defined USG && !defined GNU_LINUX \
5875 && !(defined HPUX && defined WNOHANG)))
5876 #if defined (USG) && ! defined (POSIX_SIGNALS)
5877 signal (signo, sigchld_handler);
5878 #endif
5879 errno = old_errno;
5880 return;
5881 #endif /* USG, but not HPUX with WNOHANG */
5886 static Lisp_Object
5887 exec_sentinel_unwind (data)
5888 Lisp_Object data;
5890 XPROCESS (XCAR (data))->sentinel = XCDR (data);
5891 return Qnil;
5894 static Lisp_Object
5895 exec_sentinel_error_handler (error)
5896 Lisp_Object error;
5898 cmd_error_internal (error, "error in process sentinel: ");
5899 Vinhibit_quit = Qt;
5900 update_echo_area ();
5901 Fsleep_for (make_number (2), Qnil);
5902 return Qt;
5905 static void
5906 exec_sentinel (proc, reason)
5907 Lisp_Object proc, reason;
5909 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
5910 register struct Lisp_Process *p = XPROCESS (proc);
5911 int count = SPECPDL_INDEX ();
5912 int outer_running_asynch_code = running_asynch_code;
5913 int waiting = waiting_for_user_input_p;
5915 /* No need to gcpro these, because all we do with them later
5916 is test them for EQness, and none of them should be a string. */
5917 odeactivate = Vdeactivate_mark;
5918 XSETBUFFER (obuffer, current_buffer);
5919 okeymap = current_buffer->keymap;
5921 sentinel = p->sentinel;
5922 if (NILP (sentinel))
5923 return;
5925 /* Zilch the sentinel while it's running, to avoid recursive invocations;
5926 assure that it gets restored no matter how the sentinel exits. */
5927 p->sentinel = Qnil;
5928 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
5929 /* Inhibit quit so that random quits don't screw up a running filter. */
5930 specbind (Qinhibit_quit, Qt);
5931 specbind (Qlast_nonmenu_event, Qt);
5933 /* In case we get recursively called,
5934 and we already saved the match data nonrecursively,
5935 save the same match data in safely recursive fashion. */
5936 if (outer_running_asynch_code)
5938 Lisp_Object tem;
5939 tem = Fmatch_data (Qnil, Qnil);
5940 restore_match_data ();
5941 record_unwind_protect (Fset_match_data, Fmatch_data (Qnil, Qnil));
5942 Fset_match_data (tem);
5945 /* For speed, if a search happens within this code,
5946 save the match data in a special nonrecursive fashion. */
5947 running_asynch_code = 1;
5949 internal_condition_case_1 (read_process_output_call,
5950 Fcons (sentinel,
5951 Fcons (proc, Fcons (reason, Qnil))),
5952 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5953 exec_sentinel_error_handler);
5955 /* If we saved the match data nonrecursively, restore it now. */
5956 restore_match_data ();
5957 running_asynch_code = outer_running_asynch_code;
5959 Vdeactivate_mark = odeactivate;
5961 /* Restore waiting_for_user_input_p as it was
5962 when we were called, in case the filter clobbered it. */
5963 waiting_for_user_input_p = waiting;
5965 #if 0
5966 if (! EQ (Fcurrent_buffer (), obuffer)
5967 || ! EQ (current_buffer->keymap, okeymap))
5968 #endif
5969 /* But do it only if the caller is actually going to read events.
5970 Otherwise there's no need to make him wake up, and it could
5971 cause trouble (for example it would make Fsit_for return). */
5972 if (waiting_for_user_input_p == -1)
5973 record_asynch_buffer_change ();
5975 unbind_to (count, Qnil);
5978 /* Report all recent events of a change in process status
5979 (either run the sentinel or output a message).
5980 This is usually done while Emacs is waiting for keyboard input
5981 but can be done at other times. */
5983 void
5984 status_notify ()
5986 register Lisp_Object proc, buffer;
5987 Lisp_Object tail, msg;
5988 struct gcpro gcpro1, gcpro2;
5990 tail = Qnil;
5991 msg = Qnil;
5992 /* We need to gcpro tail; if read_process_output calls a filter
5993 which deletes a process and removes the cons to which tail points
5994 from Vprocess_alist, and then causes a GC, tail is an unprotected
5995 reference. */
5996 GCPRO2 (tail, msg);
5998 /* Set this now, so that if new processes are created by sentinels
5999 that we run, we get called again to handle their status changes. */
6000 update_tick = process_tick;
6002 for (tail = Vprocess_alist; !NILP (tail); tail = Fcdr (tail))
6004 Lisp_Object symbol;
6005 register struct Lisp_Process *p;
6007 proc = Fcdr (Fcar (tail));
6008 p = XPROCESS (proc);
6010 if (XINT (p->tick) != XINT (p->update_tick))
6012 XSETINT (p->update_tick, XINT (p->tick));
6014 /* If process is still active, read any output that remains. */
6015 while (! EQ (p->filter, Qt)
6016 && ! EQ (p->status, Qconnect)
6017 && ! EQ (p->status, Qlisten)
6018 && ! EQ (p->command, Qt) /* Network process not stopped. */
6019 && XINT (p->infd) >= 0
6020 && read_process_output (proc, XINT (p->infd)) > 0);
6022 buffer = p->buffer;
6024 /* Get the text to use for the message. */
6025 if (!NILP (p->raw_status_low))
6026 update_status (p);
6027 msg = status_message (p->status);
6029 /* If process is terminated, deactivate it or delete it. */
6030 symbol = p->status;
6031 if (CONSP (p->status))
6032 symbol = XCAR (p->status);
6034 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6035 || EQ (symbol, Qclosed))
6037 if (delete_exited_processes)
6038 remove_process (proc);
6039 else
6040 deactivate_process (proc);
6043 /* The actions above may have further incremented p->tick.
6044 So set p->update_tick again
6045 so that an error in the sentinel will not cause
6046 this code to be run again. */
6047 XSETINT (p->update_tick, XINT (p->tick));
6048 /* Now output the message suitably. */
6049 if (!NILP (p->sentinel))
6050 exec_sentinel (proc, msg);
6051 /* Don't bother with a message in the buffer
6052 when a process becomes runnable. */
6053 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6055 Lisp_Object ro, tem;
6056 struct buffer *old = current_buffer;
6057 int opoint, opoint_byte;
6058 int before, before_byte;
6060 ro = XBUFFER (buffer)->read_only;
6062 /* Avoid error if buffer is deleted
6063 (probably that's why the process is dead, too) */
6064 if (NILP (XBUFFER (buffer)->name))
6065 continue;
6066 Fset_buffer (buffer);
6068 opoint = PT;
6069 opoint_byte = PT_BYTE;
6070 /* Insert new output into buffer
6071 at the current end-of-output marker,
6072 thus preserving logical ordering of input and output. */
6073 if (XMARKER (p->mark)->buffer)
6074 Fgoto_char (p->mark);
6075 else
6076 SET_PT_BOTH (ZV, ZV_BYTE);
6078 before = PT;
6079 before_byte = PT_BYTE;
6081 tem = current_buffer->read_only;
6082 current_buffer->read_only = Qnil;
6083 insert_string ("\nProcess ");
6084 Finsert (1, &p->name);
6085 insert_string (" ");
6086 Finsert (1, &msg);
6087 current_buffer->read_only = tem;
6088 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6090 if (opoint >= before)
6091 SET_PT_BOTH (opoint + (PT - before),
6092 opoint_byte + (PT_BYTE - before_byte));
6093 else
6094 SET_PT_BOTH (opoint, opoint_byte);
6096 set_buffer_internal (old);
6099 } /* end for */
6101 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6102 redisplay_preserve_echo_area (13);
6104 UNGCPRO;
6108 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6109 Sset_process_coding_system, 1, 3, 0,
6110 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6111 DECODING will be used to decode subprocess output and ENCODING to
6112 encode subprocess input. */)
6113 (proc, decoding, encoding)
6114 register Lisp_Object proc, decoding, encoding;
6116 register struct Lisp_Process *p;
6118 CHECK_PROCESS (proc);
6119 p = XPROCESS (proc);
6120 if (XINT (p->infd) < 0)
6121 error ("Input file descriptor of %s closed", SDATA (p->name));
6122 if (XINT (p->outfd) < 0)
6123 error ("Output file descriptor of %s closed", SDATA (p->name));
6125 p->decode_coding_system = Fcheck_coding_system (decoding);
6126 p->encode_coding_system = Fcheck_coding_system (encoding);
6127 setup_coding_system (decoding,
6128 proc_decode_coding_system[XINT (p->infd)]);
6129 setup_coding_system (encoding,
6130 proc_encode_coding_system[XINT (p->outfd)]);
6132 return Qnil;
6135 DEFUN ("process-coding-system",
6136 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6137 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6138 (proc)
6139 register Lisp_Object proc;
6141 CHECK_PROCESS (proc);
6142 return Fcons (XPROCESS (proc)->decode_coding_system,
6143 XPROCESS (proc)->encode_coding_system);
6146 /* The first time this is called, assume keyboard input comes from DESC
6147 instead of from where we used to expect it.
6148 Subsequent calls mean assume input keyboard can come from DESC
6149 in addition to other places. */
6151 static int add_keyboard_wait_descriptor_called_flag;
6153 void
6154 add_keyboard_wait_descriptor (desc)
6155 int desc;
6157 if (! add_keyboard_wait_descriptor_called_flag)
6158 FD_CLR (0, &input_wait_mask);
6159 add_keyboard_wait_descriptor_called_flag = 1;
6160 FD_SET (desc, &input_wait_mask);
6161 FD_SET (desc, &non_process_wait_mask);
6162 if (desc > max_keyboard_desc)
6163 max_keyboard_desc = desc;
6166 /* From now on, do not expect DESC to give keyboard input. */
6168 void
6169 delete_keyboard_wait_descriptor (desc)
6170 int desc;
6172 int fd;
6173 int lim = max_keyboard_desc;
6175 FD_CLR (desc, &input_wait_mask);
6176 FD_CLR (desc, &non_process_wait_mask);
6178 if (desc == max_keyboard_desc)
6179 for (fd = 0; fd < lim; fd++)
6180 if (FD_ISSET (fd, &input_wait_mask)
6181 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6182 max_keyboard_desc = fd;
6185 /* Return nonzero if *MASK has a bit set
6186 that corresponds to one of the keyboard input descriptors. */
6189 keyboard_bit_set (mask)
6190 SELECT_TYPE *mask;
6192 int fd;
6194 for (fd = 0; fd <= max_keyboard_desc; fd++)
6195 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6196 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6197 return 1;
6199 return 0;
6202 void
6203 init_process ()
6205 register int i;
6207 #ifdef SIGCHLD
6208 #ifndef CANNOT_DUMP
6209 if (! noninteractive || initialized)
6210 #endif
6211 signal (SIGCHLD, sigchld_handler);
6212 #endif
6214 FD_ZERO (&input_wait_mask);
6215 FD_ZERO (&non_keyboard_wait_mask);
6216 FD_ZERO (&non_process_wait_mask);
6217 max_process_desc = 0;
6219 FD_SET (0, &input_wait_mask);
6221 Vprocess_alist = Qnil;
6222 for (i = 0; i < MAXDESC; i++)
6224 chan_process[i] = Qnil;
6225 proc_buffered_char[i] = -1;
6227 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
6228 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
6229 #ifdef DATAGRAM_SOCKETS
6230 bzero (datagram_address, sizeof datagram_address);
6231 #endif
6233 #ifdef HAVE_SOCKETS
6235 Lisp_Object subfeatures = Qnil;
6236 #define ADD_SUBFEATURE(key, val) \
6237 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
6239 #ifdef NON_BLOCKING_CONNECT
6240 ADD_SUBFEATURE (QCnowait, Qt);
6241 #endif
6242 #ifdef DATAGRAM_SOCKETS
6243 ADD_SUBFEATURE (QCtype, Qdatagram);
6244 #endif
6245 #ifdef HAVE_LOCAL_SOCKETS
6246 ADD_SUBFEATURE (QCfamily, Qlocal);
6247 #endif
6248 #ifdef HAVE_GETSOCKNAME
6249 ADD_SUBFEATURE (QCservice, Qt);
6250 #endif
6251 #if !defined(TERM) && (defined(O_NONBLOCK) || defined(O_NDELAY))
6252 ADD_SUBFEATURE (QCserver, Qt);
6253 #endif
6254 #ifdef SO_BINDTODEVICE
6255 ADD_SUBFEATURE (QCoptions, intern ("bindtodevice"));
6256 #endif
6257 #ifdef SO_BROADCAST
6258 ADD_SUBFEATURE (QCoptions, intern ("broadcast"));
6259 #endif
6260 #ifdef SO_DONTROUTE
6261 ADD_SUBFEATURE (QCoptions, intern ("dontroute"));
6262 #endif
6263 #ifdef SO_KEEPALIVE
6264 ADD_SUBFEATURE (QCoptions, intern ("keepalive"));
6265 #endif
6266 #ifdef SO_LINGER
6267 ADD_SUBFEATURE (QCoptions, intern ("linger"));
6268 #endif
6269 #ifdef SO_OOBINLINE
6270 ADD_SUBFEATURE (QCoptions, intern ("oobinline"));
6271 #endif
6272 #ifdef SO_PRIORITY
6273 ADD_SUBFEATURE (QCoptions, intern ("priority"));
6274 #endif
6275 #ifdef SO_REUSEADDR
6276 ADD_SUBFEATURE (QCoptions, intern ("reuseaddr"));
6277 #endif
6278 Fprovide (intern ("make-network-process"), subfeatures);
6280 #endif /* HAVE_SOCKETS */
6283 void
6284 syms_of_process ()
6286 Qprocessp = intern ("processp");
6287 staticpro (&Qprocessp);
6288 Qrun = intern ("run");
6289 staticpro (&Qrun);
6290 Qstop = intern ("stop");
6291 staticpro (&Qstop);
6292 Qsignal = intern ("signal");
6293 staticpro (&Qsignal);
6295 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
6296 here again.
6298 Qexit = intern ("exit");
6299 staticpro (&Qexit); */
6301 Qopen = intern ("open");
6302 staticpro (&Qopen);
6303 Qclosed = intern ("closed");
6304 staticpro (&Qclosed);
6305 Qconnect = intern ("connect");
6306 staticpro (&Qconnect);
6307 Qfailed = intern ("failed");
6308 staticpro (&Qfailed);
6309 Qlisten = intern ("listen");
6310 staticpro (&Qlisten);
6311 Qlocal = intern ("local");
6312 staticpro (&Qlocal);
6313 Qdatagram = intern ("datagram");
6314 staticpro (&Qdatagram);
6316 QCname = intern (":name");
6317 staticpro (&QCname);
6318 QCbuffer = intern (":buffer");
6319 staticpro (&QCbuffer);
6320 QChost = intern (":host");
6321 staticpro (&QChost);
6322 QCservice = intern (":service");
6323 staticpro (&QCservice);
6324 QCtype = intern (":type");
6325 staticpro (&QCtype);
6326 QClocal = intern (":local");
6327 staticpro (&QClocal);
6328 QCremote = intern (":remote");
6329 staticpro (&QCremote);
6330 QCcoding = intern (":coding");
6331 staticpro (&QCcoding);
6332 QCserver = intern (":server");
6333 staticpro (&QCserver);
6334 QCnowait = intern (":nowait");
6335 staticpro (&QCnowait);
6336 QCsentinel = intern (":sentinel");
6337 staticpro (&QCsentinel);
6338 QClog = intern (":log");
6339 staticpro (&QClog);
6340 QCnoquery = intern (":noquery");
6341 staticpro (&QCnoquery);
6342 QCstop = intern (":stop");
6343 staticpro (&QCstop);
6344 QCoptions = intern (":options");
6345 staticpro (&QCoptions);
6346 QCvars = intern (":vars");
6347 staticpro (&QCvars);
6349 Qlast_nonmenu_event = intern ("last-nonmenu-event");
6350 staticpro (&Qlast_nonmenu_event);
6352 staticpro (&Vprocess_alist);
6354 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
6355 doc: /* *Non-nil means delete processes immediately when they exit.
6356 nil means don't delete them until `list-processes' is run. */);
6358 delete_exited_processes = 1;
6360 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
6361 doc: /* Control type of device used to communicate with subprocesses.
6362 Values are nil to use a pipe, or t or `pty' to use a pty.
6363 The value has no effect if the system has no ptys or if all ptys are busy:
6364 then a pipe is used in any case.
6365 The value takes effect when `start-process' is called. */);
6366 Vprocess_connection_type = Qt;
6368 defsubr (&Sprocessp);
6369 defsubr (&Sget_process);
6370 defsubr (&Sget_buffer_process);
6371 defsubr (&Sdelete_process);
6372 defsubr (&Sprocess_status);
6373 defsubr (&Sprocess_exit_status);
6374 defsubr (&Sprocess_id);
6375 defsubr (&Sprocess_name);
6376 defsubr (&Sprocess_tty_name);
6377 defsubr (&Sprocess_command);
6378 defsubr (&Sset_process_buffer);
6379 defsubr (&Sprocess_buffer);
6380 defsubr (&Sprocess_mark);
6381 defsubr (&Sset_process_filter);
6382 defsubr (&Sprocess_filter);
6383 defsubr (&Sset_process_sentinel);
6384 defsubr (&Sprocess_sentinel);
6385 defsubr (&Sset_process_window_size);
6386 defsubr (&Sset_process_inherit_coding_system_flag);
6387 defsubr (&Sprocess_inherit_coding_system_flag);
6388 defsubr (&Sset_process_query_on_exit_flag);
6389 defsubr (&Sprocess_query_on_exit_flag);
6390 defsubr (&Sprocess_contact);
6391 defsubr (&Sprocess_variable);
6392 defsubr (&Sset_process_variable);
6393 defsubr (&Slist_processes);
6394 defsubr (&Sprocess_list);
6395 defsubr (&Sstart_process);
6396 #ifdef HAVE_SOCKETS
6397 defsubr (&Sset_network_process_options);
6398 defsubr (&Smake_network_process);
6399 defsubr (&Sformat_network_address);
6400 #endif /* HAVE_SOCKETS */
6401 #ifdef DATAGRAM_SOCKETS
6402 defsubr (&Sprocess_datagram_address);
6403 defsubr (&Sset_process_datagram_address);
6404 #endif
6405 defsubr (&Saccept_process_output);
6406 defsubr (&Sprocess_send_region);
6407 defsubr (&Sprocess_send_string);
6408 defsubr (&Sinterrupt_process);
6409 defsubr (&Skill_process);
6410 defsubr (&Squit_process);
6411 defsubr (&Sstop_process);
6412 defsubr (&Scontinue_process);
6413 defsubr (&Sprocess_running_child_p);
6414 defsubr (&Sprocess_send_eof);
6415 defsubr (&Ssignal_process);
6416 defsubr (&Swaiting_for_user_input_p);
6417 /* defsubr (&Sprocess_connection); */
6418 defsubr (&Sset_process_coding_system);
6419 defsubr (&Sprocess_coding_system);
6423 #else /* not subprocesses */
6425 #include <sys/types.h>
6426 #include <errno.h>
6428 #include "lisp.h"
6429 #include "systime.h"
6430 #include "charset.h"
6431 #include "coding.h"
6432 #include "termopts.h"
6433 #include "sysselect.h"
6435 extern int frame_garbaged;
6437 extern EMACS_TIME timer_check ();
6438 extern int timers_run;
6440 Lisp_Object QCtype;
6442 /* As described above, except assuming that there are no subprocesses:
6444 Wait for timeout to elapse and/or keyboard input to be available.
6446 time_limit is:
6447 timeout in seconds, or
6448 zero for no limit, or
6449 -1 means gobble data immediately available but don't wait for any.
6451 read_kbd is a Lisp_Object:
6452 0 to ignore keyboard input, or
6453 1 to return when input is available, or
6454 -1 means caller will actually read the input, so don't throw to
6455 the quit handler.
6456 a cons cell, meaning wait until its car is non-nil
6457 (and gobble terminal input into the buffer if any arrives), or
6458 We know that read_kbd will never be a Lisp_Process, since
6459 `subprocesses' isn't defined.
6461 do_display != 0 means redisplay should be done to show subprocess
6462 output that arrives.
6464 Return true iff we received input from any process. */
6467 wait_reading_process_input (time_limit, microsecs, read_kbd, do_display)
6468 int time_limit, microsecs;
6469 Lisp_Object read_kbd;
6470 int do_display;
6472 register int nfds;
6473 EMACS_TIME end_time, timeout;
6474 SELECT_TYPE waitchannels;
6475 int xerrno;
6476 /* Either nil or a cons cell, the car of which is of interest and
6477 may be changed outside of this routine. */
6478 Lisp_Object wait_for_cell;
6480 wait_for_cell = Qnil;
6482 /* If waiting for non-nil in a cell, record where. */
6483 if (CONSP (read_kbd))
6485 wait_for_cell = read_kbd;
6486 XSETFASTINT (read_kbd, 0);
6489 /* What does time_limit really mean? */
6490 if (time_limit || microsecs)
6492 EMACS_GET_TIME (end_time);
6493 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
6494 EMACS_ADD_TIME (end_time, end_time, timeout);
6497 /* Turn off periodic alarms (in case they are in use)
6498 and then turn off any other atimers,
6499 because the select emulator uses alarms. */
6500 stop_polling ();
6501 turn_on_atimers (0);
6503 while (1)
6505 int timeout_reduced_for_timers = 0;
6507 /* If calling from keyboard input, do not quit
6508 since we want to return C-g as an input character.
6509 Otherwise, do pending quit if requested. */
6510 if (XINT (read_kbd) >= 0)
6511 QUIT;
6513 /* Exit now if the cell we're waiting for became non-nil. */
6514 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6515 break;
6517 /* Compute time from now till when time limit is up */
6518 /* Exit if already run out */
6519 if (time_limit == -1)
6521 /* -1 specified for timeout means
6522 gobble output available now
6523 but don't wait at all. */
6525 EMACS_SET_SECS_USECS (timeout, 0, 0);
6527 else if (time_limit || microsecs)
6529 EMACS_GET_TIME (timeout);
6530 EMACS_SUB_TIME (timeout, end_time, timeout);
6531 if (EMACS_TIME_NEG_P (timeout))
6532 break;
6534 else
6536 EMACS_SET_SECS_USECS (timeout, 100000, 0);
6539 /* If our caller will not immediately handle keyboard events,
6540 run timer events directly.
6541 (Callers that will immediately read keyboard events
6542 call timer_delay on their own.) */
6543 if (NILP (wait_for_cell))
6545 EMACS_TIME timer_delay;
6549 int old_timers_run = timers_run;
6550 timer_delay = timer_check (1);
6551 if (timers_run != old_timers_run && do_display)
6552 /* We must retry, since a timer may have requeued itself
6553 and that could alter the time delay. */
6554 redisplay_preserve_echo_area (14);
6555 else
6556 break;
6558 while (!detect_input_pending ());
6560 /* If there is unread keyboard input, also return. */
6561 if (XINT (read_kbd) != 0
6562 && requeued_events_pending_p ())
6563 break;
6565 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
6567 EMACS_TIME difference;
6568 EMACS_SUB_TIME (difference, timer_delay, timeout);
6569 if (EMACS_TIME_NEG_P (difference))
6571 timeout = timer_delay;
6572 timeout_reduced_for_timers = 1;
6577 /* Cause C-g and alarm signals to take immediate action,
6578 and cause input available signals to zero out timeout. */
6579 if (XINT (read_kbd) < 0)
6580 set_waiting_for_input (&timeout);
6582 /* Wait till there is something to do. */
6584 if (! XINT (read_kbd) && NILP (wait_for_cell))
6585 FD_ZERO (&waitchannels);
6586 else
6587 FD_SET (0, &waitchannels);
6589 /* If a frame has been newly mapped and needs updating,
6590 reprocess its display stuff. */
6591 if (frame_garbaged && do_display)
6593 clear_waiting_for_input ();
6594 redisplay_preserve_echo_area (15);
6595 if (XINT (read_kbd) < 0)
6596 set_waiting_for_input (&timeout);
6599 if (XINT (read_kbd) && detect_input_pending ())
6601 nfds = 0;
6602 FD_ZERO (&waitchannels);
6604 else
6605 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
6606 &timeout);
6608 xerrno = errno;
6610 /* Make C-g and alarm signals set flags again */
6611 clear_waiting_for_input ();
6613 /* If we woke up due to SIGWINCH, actually change size now. */
6614 do_pending_window_change (0);
6616 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
6617 /* We waited the full specified time, so return now. */
6618 break;
6620 if (nfds == -1)
6622 /* If the system call was interrupted, then go around the
6623 loop again. */
6624 if (xerrno == EINTR)
6625 FD_ZERO (&waitchannels);
6626 else
6627 error ("select error: %s", emacs_strerror (xerrno));
6629 #ifdef sun
6630 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
6631 /* System sometimes fails to deliver SIGIO. */
6632 kill (getpid (), SIGIO);
6633 #endif
6634 #ifdef SIGIO
6635 if (XINT (read_kbd) && interrupt_input && (waitchannels & 1))
6636 kill (getpid (), SIGIO);
6637 #endif
6639 /* Check for keyboard input */
6641 if ((XINT (read_kbd) != 0)
6642 && detect_input_pending_run_timers (do_display))
6644 swallow_events (do_display);
6645 if (detect_input_pending_run_timers (do_display))
6646 break;
6649 /* If there is unread keyboard input, also return. */
6650 if (XINT (read_kbd) != 0
6651 && requeued_events_pending_p ())
6652 break;
6654 /* If wait_for_cell. check for keyboard input
6655 but don't run any timers.
6656 ??? (It seems wrong to me to check for keyboard
6657 input at all when wait_for_cell, but the code
6658 has been this way since July 1994.
6659 Try changing this after version 19.31.) */
6660 if (! NILP (wait_for_cell)
6661 && detect_input_pending ())
6663 swallow_events (do_display);
6664 if (detect_input_pending ())
6665 break;
6668 /* Exit now if the cell we're waiting for became non-nil. */
6669 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
6670 break;
6673 start_polling ();
6675 return 0;
6679 /* Don't confuse make-docfile by having two doc strings for this function.
6680 make-docfile does not pay attention to #if, for good reason! */
6681 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
6683 (name)
6684 register Lisp_Object name;
6686 return Qnil;
6689 /* Don't confuse make-docfile by having two doc strings for this function.
6690 make-docfile does not pay attention to #if, for good reason! */
6691 DEFUN ("process-inherit-coding-system-flag",
6692 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
6693 1, 1, 0,
6695 (process)
6696 register Lisp_Object process;
6698 /* Ignore the argument and return the value of
6699 inherit-process-coding-system. */
6700 return inherit_process_coding_system ? Qt : Qnil;
6703 /* Kill all processes associated with `buffer'.
6704 If `buffer' is nil, kill all processes.
6705 Since we have no subprocesses, this does nothing. */
6707 void
6708 kill_buffer_processes (buffer)
6709 Lisp_Object buffer;
6713 void
6714 init_process ()
6718 void
6719 syms_of_process ()
6721 QCtype = intern (":type");
6722 staticpro (&QCtype);
6724 defsubr (&Sget_buffer_process);
6725 defsubr (&Sprocess_inherit_coding_system_flag);
6729 #endif /* not subprocesses */