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