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