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