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