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