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