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