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
2789 /* Used by make-serial-process to recover from errors. */
2790 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2791 {
2792 if (!PROCESSP (proc))
2793 abort ();
2794 remove_process (proc);
2795 return Qnil;
2796 }
2797
2798 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2799 0, MANY, 0,
2800 doc: /* Create and return a serial port process.
2801
2802 In Emacs, serial port connections are represented by process objects,
2803 so input and output work as for subprocesses, and `delete-process'
2804 closes a serial port connection. However, a serial process has no
2805 process id, it cannot be signaled, and the status codes are different
2806 from normal processes.
2807
2808 `make-serial-process' creates a process and a buffer, on which you
2809 probably want to use `process-send-string'. Try \\[serial-term] for
2810 an interactive terminal. See below for examples.
2811
2812 Arguments are specified as keyword/argument pairs. The following
2813 arguments are defined:
2814
2815 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2816 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2817 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2818 the backslashes in strings).
2819
2820 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2821 which is called by `make-serial-process'.
2822
2823 :name NAME -- NAME is the name of the process. If NAME is not given,
2824 the value of PORT is used.
2825
2826 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2827 with the process. Process output goes at the end of that buffer,
2828 unless you specify an output stream or filter function to handle the
2829 output. If BUFFER is not given, the value of NAME is used.
2830
2831 :coding CODING -- If CODING is a symbol, it specifies the coding
2832 system used for both reading and writing for this process. If CODING
2833 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2834 ENCODING is used for writing.
2835
2836 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2837 the process is running. If BOOL is not given, query before exiting.
2838
2839 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2840 In the stopped state, a serial process does not accept incoming data,
2841 but you can send outgoing data. The stopped state is cleared by
2842 `continue-process' and set by `stop-process'.
2843
2844 :filter FILTER -- Install FILTER as the process filter.
2845
2846 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2847
2848 :plist PLIST -- Install PLIST as the initial plist of the process.
2849
2850 :speed
2851 :bytesize
2852 :parity
2853 :stopbits
2854 :flowcontrol
2855 -- These arguments are handled by `serial-process-configure', which is
2856 called by `make-serial-process'.
2857
2858 The original argument list, possibly modified by later configuration,
2859 is available via the function `process-contact'.
2860
2861 Examples:
2862
2863 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2864
2865 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2866
2867 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2868
2869 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2870
2871 usage: (make-serial-process &rest ARGS) */)
2872 (nargs, args)
2873 int nargs;
2874 Lisp_Object *args;
2875 {
2876 int fd = -1;
2877 Lisp_Object proc, contact, port;
2878 struct Lisp_Process *p;
2879 struct gcpro gcpro1;
2880 Lisp_Object name, buffer;
2881 Lisp_Object tem, val;
2882 int specpdl_count = -1;
2883
2884 if (nargs == 0)
2885 return Qnil;
2886
2887 contact = Flist (nargs, args);
2888 GCPRO1 (contact);
2889
2890 port = Fplist_get (contact, QCport);
2891 if (NILP (port))
2892 error ("No port specified");
2893 CHECK_STRING (port);
2894
2895 if (NILP (Fplist_member (contact, QCspeed)))
2896 error (":speed not specified");
2897 if (!NILP (Fplist_get (contact, QCspeed)))
2898 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2899
2900 name = Fplist_get (contact, QCname);
2901 if (NILP (name))
2902 name = port;
2903 CHECK_STRING (name);
2904 proc = make_process (name);
2905 specpdl_count = SPECPDL_INDEX ();
2906 record_unwind_protect (make_serial_process_unwind, proc);
2907 p = XPROCESS (proc);
2908
2909 fd = serial_open ((char*) SDATA (port));
2910 p->infd = fd;
2911 p->outfd = fd;
2912 if (fd > max_process_desc)
2913 max_process_desc = fd;
2914 chan_process[fd] = proc;
2915
2916 buffer = Fplist_get (contact, QCbuffer);
2917 if (NILP (buffer))
2918 buffer = name;
2919 buffer = Fget_buffer_create (buffer);
2920 p->buffer = buffer;
2921
2922 p->childp = contact;
2923 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2924 p->type = Qserial;
2925 p->sentinel = Fplist_get (contact, QCsentinel);
2926 p->filter = Fplist_get (contact, QCfilter);
2927 p->log = Qnil;
2928 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2929 p->kill_without_query = 1;
2930 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2931 p->command = Qt;
2932 p->pty_flag = 0;
2933
2934 if (!EQ (p->command, Qt))
2935 {
2936 FD_SET (fd, &input_wait_mask);
2937 FD_SET (fd, &non_keyboard_wait_mask);
2938 }
2939
2940 if (BUFFERP (buffer))
2941 {
2942 set_marker_both (p->mark, buffer,
2943 BUF_ZV (XBUFFER (buffer)),
2944 BUF_ZV_BYTE (XBUFFER (buffer)));
2945 }
2946
2947 tem = Fplist_member (contact, QCcoding);
2948 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2949 tem = Qnil;
2950
2951 val = Qnil;
2952 if (!NILP (tem))
2953 {
2954 val = XCAR (XCDR (tem));
2955 if (CONSP (val))
2956 val = XCAR (val);
2957 }
2958 else if (!NILP (Vcoding_system_for_read))
2959 val = Vcoding_system_for_read;
2960 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2961 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2962 val = Qnil;
2963 p->decode_coding_system = val;
2964
2965 val = Qnil;
2966 if (!NILP (tem))
2967 {
2968 val = XCAR (XCDR (tem));
2969 if (CONSP (val))
2970 val = XCDR (val);
2971 }
2972 else if (!NILP (Vcoding_system_for_write))
2973 val = Vcoding_system_for_write;
2974 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2975 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2976 val = Qnil;
2977 p->encode_coding_system = val;
2978
2979 setup_process_coding_systems (proc);
2980 p->decoding_buf = make_uninit_string (0);
2981 p->decoding_carryover = 0;
2982 p->encoding_buf = make_uninit_string (0);
2983 p->inherit_coding_system_flag
2984 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2985
2986 Fserial_process_configure(nargs, args);
2987
2988 specpdl_ptr = specpdl + specpdl_count;
2989
2990 UNGCPRO;
2991 return proc;
2992 }
2993 #endif /* HAVE_SERIAL */
2994
2995 /* Create a network stream/datagram client/server process. Treated
2996 exactly like a normal process when reading and writing. Primary
2997 differences are in status display and process deletion. A network
2998 connection has no PID; you cannot signal it. All you can do is
2999 stop/continue it and deactivate/close it via delete-process */
3000
3001 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3002 0, MANY, 0,
3003 doc: /* Create and return a network server or client process.
3004
3005 In Emacs, network connections are represented by process objects, so
3006 input and output work as for subprocesses and `delete-process' closes
3007 a network connection. However, a network process has no process id,
3008 it cannot be signaled, and the status codes are different from normal
3009 processes.
3010
3011 Arguments are specified as keyword/argument pairs. The following
3012 arguments are defined:
3013
3014 :name NAME -- NAME is name for process. It is modified if necessary
3015 to make it unique.
3016
3017 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3018 with the process. Process output goes at end of that buffer, unless
3019 you specify an output stream or filter function to handle the output.
3020 BUFFER may be also nil, meaning that this process is not associated
3021 with any buffer.
3022
3023 :host HOST -- HOST is name of the host to connect to, or its IP
3024 address. The symbol `local' specifies the local host. If specified
3025 for a server process, it must be a valid name or address for the local
3026 host, and only clients connecting to that address will be accepted.
3027
3028 :service SERVICE -- SERVICE is name of the service desired, or an
3029 integer specifying a port number to connect to. If SERVICE is t,
3030 a random port number is selected for the server. (If Emacs was
3031 compiled with getaddrinfo, a port number can also be specified as a
3032 string, e.g. "80", as well as an integer. This is not portable.)
3033
3034 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3035 stream type connection, `datagram' creates a datagram type connection.
3036
3037 :family FAMILY -- FAMILY is the address (and protocol) family for the
3038 service specified by HOST and SERVICE. The default (nil) is to use
3039 whatever address family (IPv4 or IPv6) that is defined for the host
3040 and port number specified by HOST and SERVICE. Other address families
3041 supported are:
3042 local -- for a local (i.e. UNIX) address specified by SERVICE.
3043 ipv4 -- use IPv4 address family only.
3044 ipv6 -- use IPv6 address family only.
3045
3046 :local ADDRESS -- ADDRESS is the local address used for the connection.
3047 This parameter is ignored when opening a client process. When specified
3048 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3049
3050 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3051 connection. This parameter is ignored when opening a stream server
3052 process. For a datagram server process, it specifies the initial
3053 setting of the remote datagram address. When specified for a client
3054 process, the FAMILY, HOST, and SERVICE args are ignored.
3055
3056 The format of ADDRESS depends on the address family:
3057 - An IPv4 address is represented as an vector of integers [A B C D P]
3058 corresponding to numeric IP address A.B.C.D and port number P.
3059 - A local address is represented as a string with the address in the
3060 local address space.
3061 - An "unsupported family" address is represented by a cons (F . AV)
3062 where F is the family number and AV is a vector containing the socket
3063 address data with one element per address data byte. Do not rely on
3064 this format in portable code, as it may depend on implementation
3065 defined constants, data sizes, and data structure alignment.
3066
3067 :coding CODING -- If CODING is a symbol, it specifies the coding
3068 system used for both reading and writing for this process. If CODING
3069 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3070 ENCODING is used for writing.
3071
3072 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3073 return without waiting for the connection to complete; instead, the
3074 sentinel function will be called with second arg matching "open" (if
3075 successful) or "failed" when the connect completes. Default is to use
3076 a blocking connect (i.e. wait) for stream type connections.
3077
3078 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3079 running when Emacs is exited.
3080
3081 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3082 In the stopped state, a server process does not accept new
3083 connections, and a client process does not handle incoming traffic.
3084 The stopped state is cleared by `continue-process' and set by
3085 `stop-process'.
3086
3087 :filter FILTER -- Install FILTER as the process filter.
3088
3089 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3090 process filter are multibyte, otherwise they are unibyte.
3091 If this keyword is not specified, the strings are multibyte if
3092 `default-enable-multibyte-characters' is non-nil.
3093
3094 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3095
3096 :log LOG -- Install LOG as the server process log function. This
3097 function is called when the server accepts a network connection from a
3098 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3099 is the server process, CLIENT is the new process for the connection,
3100 and MESSAGE is a string.
3101
3102 :plist PLIST -- Install PLIST as the new process' initial plist.
3103
3104 :server QLEN -- if QLEN is non-nil, create a server process for the
3105 specified FAMILY, SERVICE, and connection type (stream or datagram).
3106 If QLEN is an integer, it is used as the max. length of the server's
3107 pending connection queue (also known as the backlog); the default
3108 queue length is 5. Default is to create a client process.
3109
3110 The following network options can be specified for this connection:
3111
3112 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3113 :dontroute BOOL -- Only send to directly connected hosts.
3114 :keepalive BOOL -- Send keep-alive messages on network stream.
3115 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3116 :oobinline BOOL -- Place out-of-band data in receive data stream.
3117 :priority INT -- Set protocol defined priority for sent packets.
3118 :reuseaddr BOOL -- Allow reusing a recently used local address
3119 (this is allowed by default for a server process).
3120 :bindtodevice NAME -- bind to interface NAME. Using this may require
3121 special privileges on some systems.
3122
3123 Consult the relevant system programmer's manual pages for more
3124 information on using these options.
3125
3126
3127 A server process will listen for and accept connections from clients.
3128 When a client connection is accepted, a new network process is created
3129 for the connection with the following parameters:
3130
3131 - The client's process name is constructed by concatenating the server
3132 process' NAME and a client identification string.
3133 - If the FILTER argument is non-nil, the client process will not get a
3134 separate process buffer; otherwise, the client's process buffer is a newly
3135 created buffer named after the server process' BUFFER name or process
3136 NAME concatenated with the client identification string.
3137 - The connection type and the process filter and sentinel parameters are
3138 inherited from the server process' TYPE, FILTER and SENTINEL.
3139 - The client process' contact info is set according to the client's
3140 addressing information (typically an IP address and a port number).
3141 - The client process' plist is initialized from the server's plist.
3142
3143 Notice that the FILTER and SENTINEL args are never used directly by
3144 the server process. Also, the BUFFER argument is not used directly by
3145 the server process, but via the optional :log function, accepted (and
3146 failed) connections may be logged in the server process' buffer.
3147
3148 The original argument list, modified with the actual connection
3149 information, is available via the `process-contact' function.
3150
3151 usage: (make-network-process &rest ARGS) */)
3152 (nargs, args)
3153 int nargs;
3154 Lisp_Object *args;
3155 {
3156 Lisp_Object proc;
3157 Lisp_Object contact;
3158 struct Lisp_Process *p;
3159 #ifdef HAVE_GETADDRINFO
3160 struct addrinfo ai, *res, *lres;
3161 struct addrinfo hints;
3162 char *portstring, portbuf[128];
3163 #else /* HAVE_GETADDRINFO */
3164 struct _emacs_addrinfo
3165 {
3166 int ai_family;
3167 int ai_socktype;
3168 int ai_protocol;
3169 int ai_addrlen;
3170 struct sockaddr *ai_addr;
3171 struct _emacs_addrinfo *ai_next;
3172 } ai, *res, *lres;
3173 #endif /* HAVE_GETADDRINFO */
3174 struct sockaddr_in address_in;
3175 #ifdef HAVE_LOCAL_SOCKETS
3176 struct sockaddr_un address_un;
3177 #endif
3178 int port;
3179 int ret = 0;
3180 int xerrno = 0;
3181 int s = -1, outch, inch;
3182 struct gcpro gcpro1;
3183 int count = SPECPDL_INDEX ();
3184 int count1;
3185 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3186 Lisp_Object tem;
3187 Lisp_Object name, buffer, host, service, address;
3188 Lisp_Object filter, sentinel;
3189 int is_non_blocking_client = 0;
3190 int is_server = 0, backlog = 5;
3191 int socktype;
3192 int family = -1;
3193
3194 if (nargs == 0)
3195 return Qnil;
3196
3197 /* Save arguments for process-contact and clone-process. */
3198 contact = Flist (nargs, args);
3199 GCPRO1 (contact);
3200
3201 #ifdef WINDOWSNT
3202 /* Ensure socket support is loaded if available. */
3203 init_winsock (TRUE);
3204 #endif
3205
3206 /* :type TYPE (nil: stream, datagram */
3207 tem = Fplist_get (contact, QCtype);
3208 if (NILP (tem))
3209 socktype = SOCK_STREAM;
3210 #ifdef DATAGRAM_SOCKETS
3211 else if (EQ (tem, Qdatagram))
3212 socktype = SOCK_DGRAM;
3213 #endif
3214 else
3215 error ("Unsupported connection type");
3216
3217 /* :server BOOL */
3218 tem = Fplist_get (contact, QCserver);
3219 if (!NILP (tem))
3220 {
3221 /* Don't support network sockets when non-blocking mode is
3222 not available, since a blocked Emacs is not useful. */
3223 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3224 error ("Network servers not supported");
3225 #else
3226 is_server = 1;
3227 if (INTEGERP (tem))
3228 backlog = XINT (tem);
3229 #endif
3230 }
3231
3232 /* Make QCaddress an alias for :local (server) or :remote (client). */
3233 QCaddress = is_server ? QClocal : QCremote;
3234
3235 /* :nowait BOOL */
3236 if (!is_server && socktype == SOCK_STREAM
3237 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3238 {
3239 #ifndef NON_BLOCKING_CONNECT
3240 error ("Non-blocking connect not supported");
3241 #else
3242 is_non_blocking_client = 1;
3243 #endif
3244 }
3245
3246 name = Fplist_get (contact, QCname);
3247 buffer = Fplist_get (contact, QCbuffer);
3248 filter = Fplist_get (contact, QCfilter);
3249 sentinel = Fplist_get (contact, QCsentinel);
3250
3251 CHECK_STRING (name);
3252
3253 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3254 ai.ai_socktype = socktype;
3255 ai.ai_protocol = 0;
3256 ai.ai_next = NULL;
3257 res = &ai;
3258
3259 /* :local ADDRESS or :remote ADDRESS */
3260 address = Fplist_get (contact, QCaddress);
3261 if (!NILP (address))
3262 {
3263 host = service = Qnil;
3264
3265 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3266 error ("Malformed :address");
3267 ai.ai_family = family;
3268 ai.ai_addr = alloca (ai.ai_addrlen);
3269 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3270 goto open_socket;
3271 }
3272
3273 /* :family FAMILY -- nil (for Inet), local, or integer. */
3274 tem = Fplist_get (contact, QCfamily);
3275 if (NILP (tem))
3276 {
3277 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3278 family = AF_UNSPEC;
3279 #else
3280 family = AF_INET;
3281 #endif
3282 }
3283 #ifdef HAVE_LOCAL_SOCKETS
3284 else if (EQ (tem, Qlocal))
3285 family = AF_LOCAL;
3286 #endif
3287 #ifdef AF_INET6
3288 else if (EQ (tem, Qipv6))
3289 family = AF_INET6;
3290 #endif
3291 else if (EQ (tem, Qipv4))
3292 family = AF_INET;
3293 else if (INTEGERP (tem))
3294 family = XINT (tem);
3295 else
3296 error ("Unknown address family");
3297
3298 ai.ai_family = family;
3299
3300 /* :service SERVICE -- string, integer (port number), or t (random port). */
3301 service = Fplist_get (contact, QCservice);
3302
3303 #ifdef HAVE_LOCAL_SOCKETS
3304 if (family == AF_LOCAL)
3305 {
3306 /* Host is not used. */
3307 host = Qnil;
3308 CHECK_STRING (service);
3309 bzero (&address_un, sizeof address_un);
3310 address_un.sun_family = AF_LOCAL;
3311 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3312 ai.ai_addr = (struct sockaddr *) &address_un;
3313 ai.ai_addrlen = sizeof address_un;
3314 goto open_socket;
3315 }
3316 #endif
3317
3318 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3319 host = Fplist_get (contact, QChost);
3320 if (!NILP (host))
3321 {
3322 if (EQ (host, Qlocal))
3323 host = build_string ("localhost");
3324 CHECK_STRING (host);
3325 }
3326
3327 /* Slow down polling to every ten seconds.
3328 Some kernels have a bug which causes retrying connect to fail
3329 after a connect. Polling can interfere with gethostbyname too. */
3330 #ifdef POLL_FOR_INPUT
3331 if (socktype == SOCK_STREAM)
3332 {
3333 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3334 bind_polling_period (10);
3335 }
3336 #endif
3337
3338 #ifdef HAVE_GETADDRINFO
3339 /* If we have a host, use getaddrinfo to resolve both host and service.
3340 Otherwise, use getservbyname to lookup the service. */
3341 if (!NILP (host))
3342 {
3343
3344 /* SERVICE can either be a string or int.
3345 Convert to a C string for later use by getaddrinfo. */
3346 if (EQ (service, Qt))
3347 portstring = "0";
3348 else if (INTEGERP (service))
3349 {
3350 sprintf (portbuf, "%ld", (long) XINT (service));
3351 portstring = portbuf;
3352 }
3353 else
3354 {
3355 CHECK_STRING (service);
3356 portstring = SDATA (service);
3357 }
3358
3359 immediate_quit = 1;
3360 QUIT;
3361 memset (&hints, 0, sizeof (hints));
3362 hints.ai_flags = 0;
3363 hints.ai_family = family;
3364 hints.ai_socktype = socktype;
3365 hints.ai_protocol = 0;
3366
3367 #ifdef HAVE_RES_INIT
3368 res_init ();
3369 #endif
3370
3371 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3372 if (ret)
3373 #ifdef HAVE_GAI_STRERROR
3374 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3375 #else
3376 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3377 #endif
3378 immediate_quit = 0;
3379
3380 goto open_socket;
3381 }
3382 #endif /* HAVE_GETADDRINFO */
3383
3384 /* We end up here if getaddrinfo is not defined, or in case no hostname
3385 has been specified (e.g. for a local server process). */
3386
3387 if (EQ (service, Qt))
3388 port = 0;
3389 else if (INTEGERP (service))
3390 port = htons ((unsigned short) XINT (service));
3391 else
3392 {
3393 struct servent *svc_info;
3394 CHECK_STRING (service);
3395 svc_info = getservbyname (SDATA (service),
3396 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3397 if (svc_info == 0)
3398 error ("Unknown service: %s", SDATA (service));
3399 port = svc_info->s_port;
3400 }
3401
3402 bzero (&address_in, sizeof address_in);
3403 address_in.sin_family = family;
3404 address_in.sin_addr.s_addr = INADDR_ANY;
3405 address_in.sin_port = port;
3406
3407 #ifndef HAVE_GETADDRINFO
3408 if (!NILP (host))
3409 {
3410 struct hostent *host_info_ptr;
3411
3412 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3413 as it may `hang' Emacs for a very long time. */
3414 immediate_quit = 1;
3415 QUIT;
3416
3417 #ifdef HAVE_RES_INIT
3418 res_init ();
3419 #endif
3420
3421 host_info_ptr = gethostbyname (SDATA (host));
3422 immediate_quit = 0;
3423
3424 if (host_info_ptr)
3425 {
3426 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3427 host_info_ptr->h_length);
3428 family = host_info_ptr->h_addrtype;
3429 address_in.sin_family = family;
3430 }
3431 else
3432 /* Attempt to interpret host as numeric inet address */
3433 {
3434 unsigned long numeric_addr;
3435 numeric_addr = inet_addr ((char *) SDATA (host));
3436 if (numeric_addr == -1)
3437 error ("Unknown host \"%s\"", SDATA (host));
3438
3439 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3440 sizeof (address_in.sin_addr));
3441 }
3442
3443 }
3444 #endif /* not HAVE_GETADDRINFO */
3445
3446 ai.ai_family = family;
3447 ai.ai_addr = (struct sockaddr *) &address_in;
3448 ai.ai_addrlen = sizeof address_in;
3449
3450 open_socket:
3451
3452 /* Do this in case we never enter the for-loop below. */
3453 count1 = SPECPDL_INDEX ();
3454 s = -1;
3455
3456 for (lres = res; lres; lres = lres->ai_next)
3457 {
3458 int optn, optbits;
3459
3460 retry_connect:
3461
3462 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3463 if (s < 0)
3464 {
3465 xerrno = errno;
3466 continue;
3467 }
3468
3469 #ifdef DATAGRAM_SOCKETS
3470 if (!is_server && socktype == SOCK_DGRAM)
3471 break;
3472 #endif /* DATAGRAM_SOCKETS */
3473
3474 #ifdef NON_BLOCKING_CONNECT
3475 if (is_non_blocking_client)
3476 {
3477 #ifdef O_NONBLOCK
3478 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3479 #else
3480 ret = fcntl (s, F_SETFL, O_NDELAY);
3481 #endif
3482 if (ret < 0)
3483 {
3484 xerrno = errno;
3485 emacs_close (s);
3486 s = -1;
3487 continue;
3488 }
3489 }
3490 #endif
3491
3492 /* Make us close S if quit. */
3493 record_unwind_protect (close_file_unwind, make_number (s));
3494
3495 /* Parse network options in the arg list.
3496 We simply ignore anything which isn't a known option (including other keywords).
3497 An error is signaled if setting a known option fails. */
3498 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3499 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3500
3501 if (is_server)
3502 {
3503 /* Configure as a server socket. */
3504
3505 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3506 explicit :reuseaddr key to override this. */
3507 #ifdef HAVE_LOCAL_SOCKETS
3508 if (family != AF_LOCAL)
3509 #endif
3510 if (!(optbits & (1 << OPIX_REUSEADDR)))
3511 {
3512 int optval = 1;
3513 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3514 report_file_error ("Cannot set reuse option on server socket", Qnil);
3515 }
3516
3517 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3518 report_file_error ("Cannot bind server socket", Qnil);
3519
3520 #ifdef HAVE_GETSOCKNAME
3521 if (EQ (service, Qt))
3522 {
3523 struct sockaddr_in sa1;
3524 int len1 = sizeof (sa1);
3525 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3526 {
3527 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3528 service = make_number (ntohs (sa1.sin_port));
3529 contact = Fplist_put (contact, QCservice, service);
3530 }
3531 }
3532 #endif
3533
3534 if (socktype == SOCK_STREAM && listen (s, backlog))
3535 report_file_error ("Cannot listen on server socket", Qnil);
3536
3537 break;
3538 }
3539
3540 immediate_quit = 1;
3541 QUIT;
3542
3543 /* This turns off all alarm-based interrupts; the
3544 bind_polling_period call above doesn't always turn all the
3545 short-interval ones off, especially if interrupt_input is
3546 set.
3547
3548 It'd be nice to be able to control the connect timeout
3549 though. Would non-blocking connect calls be portable?
3550
3551 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3552
3553 turn_on_atimers (0);
3554
3555 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3556 xerrno = errno;
3557
3558 turn_on_atimers (1);
3559
3560 if (ret == 0 || xerrno == EISCONN)
3561 {
3562 /* The unwind-protect will be discarded afterwards.
3563 Likewise for immediate_quit. */
3564 break;
3565 }
3566
3567 #ifdef NON_BLOCKING_CONNECT
3568 #ifdef EINPROGRESS
3569 if (is_non_blocking_client && xerrno == EINPROGRESS)
3570 break;
3571 #else
3572 #ifdef EWOULDBLOCK
3573 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3574 break;
3575 #endif
3576 #endif
3577 #endif
3578
3579 immediate_quit = 0;
3580
3581 /* Discard the unwind protect closing S. */
3582 specpdl_ptr = specpdl + count1;
3583 emacs_close (s);
3584 s = -1;
3585
3586 if (xerrno == EINTR)
3587 goto retry_connect;
3588 }
3589
3590 if (s >= 0)
3591 {
3592 #ifdef DATAGRAM_SOCKETS
3593 if (socktype == SOCK_DGRAM)
3594 {
3595 if (datagram_address[s].sa)
3596 abort ();
3597 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3598 datagram_address[s].len = lres->ai_addrlen;
3599 if (is_server)
3600 {
3601 Lisp_Object remote;
3602 bzero (datagram_address[s].sa, lres->ai_addrlen);
3603 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3604 {
3605 int rfamily, rlen;
3606 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3607 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3608 conv_lisp_to_sockaddr (rfamily, remote,
3609 datagram_address[s].sa, rlen);
3610 }
3611 }
3612 else
3613 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3614 }
3615 #endif
3616 contact = Fplist_put (contact, QCaddress,
3617 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3618 #ifdef HAVE_GETSOCKNAME
3619 if (!is_server)
3620 {
3621 struct sockaddr_in sa1;
3622 int len1 = sizeof (sa1);
3623 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3624 contact = Fplist_put (contact, QClocal,
3625 conv_sockaddr_to_lisp (&sa1, len1));
3626 }
3627 #endif
3628 }
3629
3630 immediate_quit = 0;
3631
3632 #ifdef HAVE_GETADDRINFO
3633 if (res != &ai)
3634 {
3635 BLOCK_INPUT;
3636 freeaddrinfo (res);
3637 UNBLOCK_INPUT;
3638 }
3639 #endif
3640
3641 /* Discard the unwind protect for closing S, if any. */
3642 specpdl_ptr = specpdl + count1;
3643
3644 /* Unwind bind_polling_period and request_sigio. */
3645 unbind_to (count, Qnil);
3646
3647 if (s < 0)
3648 {
3649 /* If non-blocking got this far - and failed - assume non-blocking is
3650 not supported after all. This is probably a wrong assumption, but
3651 the normal blocking calls to open-network-stream handles this error
3652 better. */
3653 if (is_non_blocking_client)
3654 return Qnil;
3655
3656 errno = xerrno;
3657 if (is_server)
3658 report_file_error ("make server process failed", contact);
3659 else
3660 report_file_error ("make client process failed", contact);
3661 }
3662
3663 inch = s;
3664 outch = s;
3665
3666 if (!NILP (buffer))
3667 buffer = Fget_buffer_create (buffer);
3668 proc = make_process (name);
3669
3670 chan_process[inch] = proc;
3671
3672 #ifdef O_NONBLOCK
3673 fcntl (inch, F_SETFL, O_NONBLOCK);
3674 #else
3675 #ifdef O_NDELAY
3676 fcntl (inch, F_SETFL, O_NDELAY);
3677 #endif
3678 #endif
3679
3680 p = XPROCESS (proc);
3681
3682 p->childp = contact;
3683 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3684 p->type = Qnetwork;
3685
3686 p->buffer = buffer;
3687 p->sentinel = sentinel;
3688 p->filter = filter;
3689 p->log = Fplist_get (contact, QClog);
3690 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3691 p->kill_without_query = 1;
3692 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3693 p->command = Qt;
3694 p->pid = 0;
3695 p->infd = inch;
3696 p->outfd = outch;
3697 if (is_server && socktype == SOCK_STREAM)
3698 p->status = Qlisten;
3699
3700 /* Make the process marker point into the process buffer (if any). */
3701 if (BUFFERP (buffer))
3702 set_marker_both (p->mark, buffer,
3703 BUF_ZV (XBUFFER (buffer)),
3704 BUF_ZV_BYTE (XBUFFER (buffer)));
3705
3706 #ifdef NON_BLOCKING_CONNECT
3707 if (is_non_blocking_client)
3708 {
3709 /* We may get here if connect did succeed immediately. However,
3710 in that case, we still need to signal this like a non-blocking
3711 connection. */
3712 p->status = Qconnect;
3713 if (!FD_ISSET (inch, &connect_wait_mask))
3714 {
3715 FD_SET (inch, &connect_wait_mask);
3716 num_pending_connects++;
3717 }
3718 }
3719 else
3720 #endif
3721 /* A server may have a client filter setting of Qt, but it must
3722 still listen for incoming connects unless it is stopped. */
3723 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3724 || (EQ (p->status, Qlisten) && NILP (p->command)))
3725 {
3726 FD_SET (inch, &input_wait_mask);
3727 FD_SET (inch, &non_keyboard_wait_mask);
3728 }
3729
3730 if (inch > max_process_desc)
3731 max_process_desc = inch;
3732
3733 tem = Fplist_member (contact, QCcoding);
3734 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3735 tem = Qnil; /* No error message (too late!). */
3736
3737 {
3738 /* Setup coding systems for communicating with the network stream. */
3739 struct gcpro gcpro1;
3740 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3741 Lisp_Object coding_systems = Qt;
3742 Lisp_Object args[5], val;
3743
3744 if (!NILP (tem))
3745 {
3746 val = XCAR (XCDR (tem));
3747 if (CONSP (val))
3748 val = XCAR (val);
3749 }
3750 else if (!NILP (Vcoding_system_for_read))
3751 val = Vcoding_system_for_read;
3752 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3753 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3754 /* We dare not decode end-of-line format by setting VAL to
3755 Qraw_text, because the existing Emacs Lisp libraries
3756 assume that they receive bare code including a sequene of
3757 CR LF. */
3758 val = Qnil;
3759 else
3760 {
3761 if (NILP (host) || NILP (service))
3762 coding_systems = Qnil;
3763 else
3764 {
3765 args[0] = Qopen_network_stream, args[1] = name,
3766 args[2] = buffer, args[3] = host, args[4] = service;
3767 GCPRO1 (proc);
3768 coding_systems = Ffind_operation_coding_system (5, args);
3769 UNGCPRO;
3770 }
3771 if (CONSP (coding_systems))
3772 val = XCAR (coding_systems);
3773 else if (CONSP (Vdefault_process_coding_system))
3774 val = XCAR (Vdefault_process_coding_system);
3775 else
3776 val = Qnil;
3777 }
3778 p->decode_coding_system = val;
3779
3780 if (!NILP (tem))
3781 {
3782 val = XCAR (XCDR (tem));
3783 if (CONSP (val))
3784 val = XCDR (val);
3785 }
3786 else if (!NILP (Vcoding_system_for_write))
3787 val = Vcoding_system_for_write;
3788 else if (NILP (current_buffer->enable_multibyte_characters))
3789 val = Qnil;
3790 else
3791 {
3792 if (EQ (coding_systems, Qt))
3793 {
3794 if (NILP (host) || NILP (service))
3795 coding_systems = Qnil;
3796 else
3797 {
3798 args[0] = Qopen_network_stream, args[1] = name,
3799 args[2] = buffer, args[3] = host, args[4] = service;
3800 GCPRO1 (proc);
3801 coding_systems = Ffind_operation_coding_system (5, args);
3802 UNGCPRO;
3803 }
3804 }
3805 if (CONSP (coding_systems))
3806 val = XCDR (coding_systems);
3807 else if (CONSP (Vdefault_process_coding_system))
3808 val = XCDR (Vdefault_process_coding_system);
3809 else
3810 val = Qnil;
3811 }
3812 p->encode_coding_system = val;
3813 }
3814 setup_process_coding_systems (proc);
3815
3816 p->decoding_buf = make_uninit_string (0);
3817 p->decoding_carryover = 0;
3818 p->encoding_buf = make_uninit_string (0);
3819
3820 p->inherit_coding_system_flag
3821 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3822
3823 UNGCPRO;
3824 return proc;
3825 }
3826 #endif /* HAVE_SOCKETS */
3827
3828 \f
3829 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3830
3831 #ifdef SIOCGIFCONF
3832 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3833 doc: /* Return an alist of all network interfaces and their network address.
3834 Each element is a cons, the car of which is a string containing the
3835 interface name, and the cdr is the network address in internal
3836 format; see the description of ADDRESS in `make-network-process'. */)
3837 ()
3838 {
3839 struct ifconf ifconf;
3840 struct ifreq *ifreqs = NULL;
3841 int ifaces = 0;
3842 int buf_size, s;
3843 Lisp_Object res;
3844
3845 s = socket (AF_INET, SOCK_STREAM, 0);
3846 if (s < 0)
3847 return Qnil;
3848
3849 again:
3850 ifaces += 25;
3851 buf_size = ifaces * sizeof(ifreqs[0]);
3852 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3853 if (!ifreqs)
3854 {
3855 close (s);
3856 return Qnil;
3857 }
3858
3859 ifconf.ifc_len = buf_size;
3860 ifconf.ifc_req = ifreqs;
3861 if (ioctl (s, SIOCGIFCONF, &ifconf))
3862 {
3863 close (s);
3864 return Qnil;
3865 }
3866
3867 if (ifconf.ifc_len == buf_size)
3868 goto again;
3869
3870 close (s);
3871 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3872
3873 res = Qnil;
3874 while (--ifaces >= 0)
3875 {
3876 struct ifreq *ifq = &ifreqs[ifaces];
3877 char namebuf[sizeof (ifq->ifr_name) + 1];
3878 if (ifq->ifr_addr.sa_family != AF_INET)
3879 continue;
3880 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3881 namebuf[sizeof (ifq->ifr_name)] = 0;
3882 res = Fcons (Fcons (build_string (namebuf),
3883 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3884 sizeof (struct sockaddr))),
3885 res);
3886 }
3887
3888 return res;
3889 }
3890 #endif /* SIOCGIFCONF */
3891
3892 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3893
3894 struct ifflag_def {
3895 int flag_bit;
3896 char *flag_sym;
3897 };
3898
3899 static struct ifflag_def ifflag_table[] = {
3900 #ifdef IFF_UP
3901 { IFF_UP, "up" },
3902 #endif
3903 #ifdef IFF_BROADCAST
3904 { IFF_BROADCAST, "broadcast" },
3905 #endif
3906 #ifdef IFF_DEBUG
3907 { IFF_DEBUG, "debug" },
3908 #endif
3909 #ifdef IFF_LOOPBACK
3910 { IFF_LOOPBACK, "loopback" },
3911 #endif
3912 #ifdef IFF_POINTOPOINT
3913 { IFF_POINTOPOINT, "pointopoint" },
3914 #endif
3915 #ifdef IFF_RUNNING
3916 { IFF_RUNNING, "running" },
3917 #endif
3918 #ifdef IFF_NOARP
3919 { IFF_NOARP, "noarp" },
3920 #endif
3921 #ifdef IFF_PROMISC
3922 { IFF_PROMISC, "promisc" },
3923 #endif
3924 #ifdef IFF_NOTRAILERS
3925 { IFF_NOTRAILERS, "notrailers" },
3926 #endif
3927 #ifdef IFF_ALLMULTI
3928 { IFF_ALLMULTI, "allmulti" },
3929 #endif
3930 #ifdef IFF_MASTER
3931 { IFF_MASTER, "master" },
3932 #endif
3933 #ifdef IFF_SLAVE
3934 { IFF_SLAVE, "slave" },
3935 #endif
3936 #ifdef IFF_MULTICAST
3937 { IFF_MULTICAST, "multicast" },
3938 #endif
3939 #ifdef IFF_PORTSEL
3940 { IFF_PORTSEL, "portsel" },
3941 #endif
3942 #ifdef IFF_AUTOMEDIA
3943 { IFF_AUTOMEDIA, "automedia" },
3944 #endif
3945 #ifdef IFF_DYNAMIC
3946 { IFF_DYNAMIC, "dynamic" },
3947 #endif
3948 #ifdef IFF_OACTIVE
3949 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3950 #endif
3951 #ifdef IFF_SIMPLEX
3952 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3953 #endif
3954 #ifdef IFF_LINK0
3955 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3956 #endif
3957 #ifdef IFF_LINK1
3958 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3959 #endif
3960 #ifdef IFF_LINK2
3961 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3962 #endif
3963 { 0, 0 }
3964 };
3965
3966 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3967 doc: /* Return information about network interface named IFNAME.
3968 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3969 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3970 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3971 FLAGS is the current flags of the interface. */)
3972 (ifname)
3973 Lisp_Object ifname;
3974 {
3975 struct ifreq rq;
3976 Lisp_Object res = Qnil;
3977 Lisp_Object elt;
3978 int s;
3979 int any = 0;
3980
3981 CHECK_STRING (ifname);
3982
3983 bzero (rq.ifr_name, sizeof rq.ifr_name);
3984 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3985
3986 s = socket (AF_INET, SOCK_STREAM, 0);
3987 if (s < 0)
3988 return Qnil;
3989
3990 elt = Qnil;
3991 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3992 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3993 {
3994 int flags = rq.ifr_flags;
3995 struct ifflag_def *fp;
3996 int fnum;
3997
3998 any++;
3999 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4000 {
4001 if (flags & fp->flag_bit)
4002 {
4003 elt = Fcons (intern (fp->flag_sym), elt);
4004 flags -= fp->flag_bit;
4005 }
4006 }
4007 for (fnum = 0; flags && fnum < 32; fnum++)
4008 {
4009 if (flags & (1 << fnum))
4010 {
4011 elt = Fcons (make_number (fnum), elt);
4012 }
4013 }
4014 }
4015 #endif
4016 res = Fcons (elt, res);
4017
4018 elt = Qnil;
4019 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4020 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4021 {
4022 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4023 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4024 int n;
4025
4026 any++;
4027 for (n = 0; n < 6; n++)
4028 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4029 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4030 }
4031 #endif
4032 res = Fcons (elt, res);
4033
4034 elt = Qnil;
4035 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4036 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4037 {
4038 any++;
4039 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4040 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4041 #else
4042 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4043 #endif
4044 }
4045 #endif
4046 res = Fcons (elt, res);
4047
4048 elt = Qnil;
4049 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4050 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4051 {
4052 any++;
4053 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4054 }
4055 #endif
4056 res = Fcons (elt, res);
4057
4058 elt = Qnil;
4059 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4060 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4061 {
4062 any++;
4063 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4064 }
4065 #endif
4066 res = Fcons (elt, res);
4067
4068 close (s);
4069
4070 return any ? res : Qnil;
4071 }
4072 #endif
4073 #endif /* HAVE_SOCKETS */
4074
4075 /* Turn off input and output for process PROC. */
4076
4077 void
4078 deactivate_process (proc)
4079 Lisp_Object proc;
4080 {
4081 register int inchannel, outchannel;
4082 register struct Lisp_Process *p = XPROCESS (proc);
4083
4084 inchannel = p->infd;
4085 outchannel = p->outfd;
4086
4087 #ifdef ADAPTIVE_READ_BUFFERING
4088 if (p->read_output_delay > 0)
4089 {
4090 if (--process_output_delay_count < 0)
4091 process_output_delay_count = 0;
4092 p->read_output_delay = 0;
4093 p->read_output_skip = 0;
4094 }
4095 #endif
4096
4097 if (inchannel >= 0)
4098 {
4099 /* Beware SIGCHLD hereabouts. */
4100 flush_pending_output (inchannel);
4101 #ifdef VMS
4102 {
4103 VMS_PROC_STUFF *get_vms_process_pointer (), *vs;
4104 sys$dassgn (outchannel);
4105 vs = get_vms_process_pointer (p->pid);
4106 if (vs)
4107 give_back_vms_process_stuff (vs);
4108 }
4109 #else
4110 emacs_close (inchannel);
4111 if (outchannel >= 0 && outchannel != inchannel)
4112 emacs_close (outchannel);
4113 #endif
4114
4115 p->infd = -1;
4116 p->outfd = -1;
4117 #ifdef DATAGRAM_SOCKETS
4118 if (DATAGRAM_CHAN_P (inchannel))
4119 {
4120 xfree (datagram_address[inchannel].sa);
4121 datagram_address[inchannel].sa = 0;
4122 datagram_address[inchannel].len = 0;
4123 }
4124 #endif
4125 chan_process[inchannel] = Qnil;
4126 FD_CLR (inchannel, &input_wait_mask);
4127 FD_CLR (inchannel, &non_keyboard_wait_mask);
4128 #ifdef NON_BLOCKING_CONNECT
4129 if (FD_ISSET (inchannel, &connect_wait_mask))
4130 {
4131 FD_CLR (inchannel, &connect_wait_mask);
4132 if (--num_pending_connects < 0)
4133 abort ();
4134 }
4135 #endif
4136 if (inchannel == max_process_desc)
4137 {
4138 int i;
4139 /* We just closed the highest-numbered process input descriptor,
4140 so recompute the highest-numbered one now. */
4141 max_process_desc = 0;
4142 for (i = 0; i < MAXDESC; i++)
4143 if (!NILP (chan_process[i]))
4144 max_process_desc = i;
4145 }
4146 }
4147 }
4148
4149 /* Close all descriptors currently in use for communication
4150 with subprocess. This is used in a newly-forked subprocess
4151 to get rid of irrelevant descriptors. */
4152
4153 void
4154 close_process_descs ()
4155 {
4156 #ifndef WINDOWSNT
4157 int i;
4158 for (i = 0; i < MAXDESC; i++)
4159 {
4160 Lisp_Object process;
4161 process = chan_process[i];
4162 if (!NILP (process))
4163 {
4164 int in = XPROCESS (process)->infd;
4165 int out = XPROCESS (process)->outfd;
4166 if (in >= 0)
4167 emacs_close (in);
4168 if (out >= 0 && in != out)
4169 emacs_close (out);
4170 }
4171 }
4172 #endif
4173 }
4174 \f
4175 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4176 0, 4, 0,
4177 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4178 It is read into the process' buffers or given to their filter functions.
4179 Non-nil arg PROCESS means do not return until some output has been received
4180 from PROCESS.
4181
4182 Non-nil second arg SECONDS and third arg MILLISEC are number of
4183 seconds and milliseconds to wait; return after that much time whether
4184 or not there is input. If SECONDS is a floating point number,
4185 it specifies a fractional number of seconds to wait.
4186 The MILLISEC argument is obsolete and should be avoided.
4187
4188 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4189 from PROCESS, suspending reading output from other processes.
4190 If JUST-THIS-ONE is an integer, don't run any timers either.
4191 Return non-nil if we received any output before the timeout expired. */)
4192 (process, seconds, millisec, just_this_one)
4193 register Lisp_Object process, seconds, millisec, just_this_one;
4194 {
4195 int secs, usecs = 0;
4196
4197 if (! NILP (process))
4198 CHECK_PROCESS (process);
4199 else
4200 just_this_one = Qnil;
4201
4202 if (!NILP (millisec))
4203 { /* Obsolete calling convention using integers rather than floats. */
4204 CHECK_NUMBER (millisec);
4205 if (NILP (seconds))
4206 seconds = make_float (XINT (millisec) / 1000.0);
4207 else
4208 {
4209 CHECK_NUMBER (seconds);
4210 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4211 }
4212 }
4213
4214 if (!NILP (seconds))
4215 {
4216 if (INTEGERP (seconds))
4217 secs = XINT (seconds);
4218 else if (FLOATP (seconds))
4219 {
4220 double timeout = XFLOAT_DATA (seconds);
4221 secs = (int) timeout;
4222 usecs = (int) ((timeout - (double) secs) * 1000000);
4223 }
4224 else
4225 wrong_type_argument (Qnumberp, seconds);
4226
4227 if (secs < 0 || (secs == 0 && usecs == 0))
4228 secs = -1, usecs = 0;
4229 }
4230 else
4231 secs = NILP (process) ? -1 : 0;
4232
4233 return
4234 (wait_reading_process_output (secs, usecs, 0, 0,
4235 Qnil,
4236 !NILP (process) ? XPROCESS (process) : NULL,
4237 NILP (just_this_one) ? 0 :
4238 !INTEGERP (just_this_one) ? 1 : -1)
4239 ? Qt : Qnil);
4240 }
4241
4242 /* Accept a connection for server process SERVER on CHANNEL. */
4243
4244 static int connect_counter = 0;
4245
4246 static void
4247 server_accept_connection (server, channel)
4248 Lisp_Object server;
4249 int channel;
4250 {
4251 Lisp_Object proc, caller, name, buffer;
4252 Lisp_Object contact, host, service;
4253 struct Lisp_Process *ps= XPROCESS (server);
4254 struct Lisp_Process *p;
4255 int s;
4256 union u_sockaddr {
4257 struct sockaddr sa;
4258 struct sockaddr_in in;
4259 #ifdef AF_INET6
4260 struct sockaddr_in6 in6;
4261 #endif
4262 #ifdef HAVE_LOCAL_SOCKETS
4263 struct sockaddr_un un;
4264 #endif
4265 } saddr;
4266 int len = sizeof saddr;
4267
4268 s = accept (channel, &saddr.sa, &len);
4269
4270 if (s < 0)
4271 {
4272 int code = errno;
4273
4274 if (code == EAGAIN)
4275 return;
4276 #ifdef EWOULDBLOCK
4277 if (code == EWOULDBLOCK)
4278 return;
4279 #endif
4280
4281 if (!NILP (ps->log))
4282 call3 (ps->log, server, Qnil,
4283 concat3 (build_string ("accept failed with code"),
4284 Fnumber_to_string (make_number (code)),
4285 build_string ("\n")));
4286 return;
4287 }
4288
4289 connect_counter++;
4290
4291 /* Setup a new process to handle the connection. */
4292
4293 /* Generate a unique identification of the caller, and build contact
4294 information for this process. */
4295 host = Qt;
4296 service = Qnil;
4297 switch (saddr.sa.sa_family)
4298 {
4299 case AF_INET:
4300 {
4301 Lisp_Object args[5];
4302 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4303 args[0] = build_string ("%d.%d.%d.%d");
4304 args[1] = make_number (*ip++);
4305 args[2] = make_number (*ip++);
4306 args[3] = make_number (*ip++);
4307 args[4] = make_number (*ip++);
4308 host = Fformat (5, args);
4309 service = make_number (ntohs (saddr.in.sin_port));
4310
4311 args[0] = build_string (" <%s:%d>");
4312 args[1] = host;
4313 args[2] = service;
4314 caller = Fformat (3, args);
4315 }
4316 break;
4317
4318 #ifdef AF_INET6
4319 case AF_INET6:
4320 {
4321 Lisp_Object args[9];
4322 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4323 int i;
4324 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4325 for (i = 0; i < 8; i++)
4326 args[i+1] = make_number (ntohs(ip6[i]));
4327 host = Fformat (9, args);
4328 service = make_number (ntohs (saddr.in.sin_port));
4329
4330 args[0] = build_string (" <[%s]:%d>");
4331 args[1] = host;
4332 args[2] = service;
4333 caller = Fformat (3, args);
4334 }
4335 break;
4336 #endif
4337
4338 #ifdef HAVE_LOCAL_SOCKETS
4339 case AF_LOCAL:
4340 #endif
4341 default:
4342 caller = Fnumber_to_string (make_number (connect_counter));
4343 caller = concat3 (build_string (" <"), caller, build_string (">"));
4344 break;
4345 }
4346
4347 /* Create a new buffer name for this process if it doesn't have a
4348 filter. The new buffer name is based on the buffer name or
4349 process name of the server process concatenated with the caller
4350 identification. */
4351
4352 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4353 buffer = Qnil;
4354 else
4355 {
4356 buffer = ps->buffer;
4357 if (!NILP (buffer))
4358 buffer = Fbuffer_name (buffer);
4359 else
4360 buffer = ps->name;
4361 if (!NILP (buffer))
4362 {
4363 buffer = concat2 (buffer, caller);
4364 buffer = Fget_buffer_create (buffer);
4365 }
4366 }
4367
4368 /* Generate a unique name for the new server process. Combine the
4369 server process name with the caller identification. */
4370
4371 name = concat2 (ps->name, caller);
4372 proc = make_process (name);
4373
4374 chan_process[s] = proc;
4375
4376 #ifdef O_NONBLOCK
4377 fcntl (s, F_SETFL, O_NONBLOCK);
4378 #else
4379 #ifdef O_NDELAY
4380 fcntl (s, F_SETFL, O_NDELAY);
4381 #endif
4382 #endif
4383
4384 p = XPROCESS (proc);
4385
4386 /* Build new contact information for this setup. */
4387 contact = Fcopy_sequence (ps->childp);
4388 contact = Fplist_put (contact, QCserver, Qnil);
4389 contact = Fplist_put (contact, QChost, host);
4390 if (!NILP (service))
4391 contact = Fplist_put (contact, QCservice, service);
4392 contact = Fplist_put (contact, QCremote,
4393 conv_sockaddr_to_lisp (&saddr.sa, len));
4394 #ifdef HAVE_GETSOCKNAME
4395 len = sizeof saddr;
4396 if (getsockname (s, &saddr.sa, &len) == 0)
4397 contact = Fplist_put (contact, QClocal,
4398 conv_sockaddr_to_lisp (&saddr.sa, len));
4399 #endif
4400
4401 p->childp = contact;
4402 p->plist = Fcopy_sequence (ps->plist);
4403 p->type = Qnetwork;
4404
4405 p->buffer = buffer;
4406 p->sentinel = ps->sentinel;
4407 p->filter = ps->filter;
4408 p->command = Qnil;
4409 p->pid = 0;
4410 p->infd = s;
4411 p->outfd = s;
4412 p->status = Qrun;
4413
4414 /* Client processes for accepted connections are not stopped initially. */
4415 if (!EQ (p->filter, Qt))
4416 {
4417 FD_SET (s, &input_wait_mask);
4418 FD_SET (s, &non_keyboard_wait_mask);
4419 }
4420
4421 if (s > max_process_desc)
4422 max_process_desc = s;
4423
4424 /* Setup coding system for new process based on server process.
4425 This seems to be the proper thing to do, as the coding system
4426 of the new process should reflect the settings at the time the
4427 server socket was opened; not the current settings. */
4428
4429 p->decode_coding_system = ps->decode_coding_system;
4430 p->encode_coding_system = ps->encode_coding_system;
4431 setup_process_coding_systems (proc);
4432
4433 p->decoding_buf = make_uninit_string (0);
4434 p->decoding_carryover = 0;
4435 p->encoding_buf = make_uninit_string (0);
4436
4437 p->inherit_coding_system_flag
4438 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4439
4440 if (!NILP (ps->log))
4441 call3 (ps->log, server, proc,
4442 concat3 (build_string ("accept from "),
4443 (STRINGP (host) ? host : build_string ("-")),
4444 build_string ("\n")));
4445
4446 if (!NILP (p->sentinel))
4447 exec_sentinel (proc,
4448 concat3 (build_string ("open from "),
4449 (STRINGP (host) ? host : build_string ("-")),
4450 build_string ("\n")));
4451 }
4452
4453 /* This variable is different from waiting_for_input in keyboard.c.
4454 It is used to communicate to a lisp process-filter/sentinel (via the
4455 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4456 for user-input when that process-filter was called.
4457 waiting_for_input cannot be used as that is by definition 0 when
4458 lisp code is being evalled.
4459 This is also used in record_asynch_buffer_change.
4460 For that purpose, this must be 0
4461 when not inside wait_reading_process_output. */
4462 static int waiting_for_user_input_p;
4463
4464 static Lisp_Object
4465 wait_reading_process_output_unwind (data)
4466 Lisp_Object data;
4467 {
4468 waiting_for_user_input_p = XINT (data);
4469 return Qnil;
4470 }
4471
4472 /* This is here so breakpoints can be put on it. */
4473 static void
4474 wait_reading_process_output_1 ()
4475 {
4476 }
4477
4478 /* Use a wrapper around select to work around a bug in gdb 5.3.
4479 Normally, the wrapper is optimzed away by inlining.
4480
4481 If emacs is stopped inside select, the gdb backtrace doesn't
4482 show the function which called select, so it is practically
4483 impossible to step through wait_reading_process_output. */
4484
4485 #ifndef select
4486 static INLINE int
4487 select_wrapper (n, rfd, wfd, xfd, tmo)
4488 int n;
4489 SELECT_TYPE *rfd, *wfd, *xfd;
4490 EMACS_TIME *tmo;
4491 {
4492 return select (n, rfd, wfd, xfd, tmo);
4493 }
4494 #define select select_wrapper
4495 #endif
4496
4497 /* Read and dispose of subprocess output while waiting for timeout to
4498 elapse and/or keyboard input to be available.
4499
4500 TIME_LIMIT is:
4501 timeout in seconds, or
4502 zero for no limit, or
4503 -1 means gobble data immediately available but don't wait for any.
4504
4505 MICROSECS is:
4506 an additional duration to wait, measured in microseconds.
4507 If this is nonzero and time_limit is 0, then the timeout
4508 consists of MICROSECS only.
4509
4510 READ_KBD is a lisp value:
4511 0 to ignore keyboard input, or
4512 1 to return when input is available, or
4513 -1 meaning caller will actually read the input, so don't throw to
4514 the quit handler, or
4515
4516 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4517 output that arrives.
4518
4519 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4520 (and gobble terminal input into the buffer if any arrives).
4521
4522 If WAIT_PROC is specified, wait until something arrives from that
4523 process. The return value is true if we read some input from
4524 that process.
4525
4526 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4527 (suspending output from other processes). A negative value
4528 means don't run any timers either.
4529
4530 If WAIT_PROC is specified, then the function returns true if we
4531 received input from that process before the timeout elapsed.
4532 Otherwise, return true if we received input from any process. */
4533
4534 int
4535 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4536 wait_for_cell, wait_proc, just_wait_proc)
4537 int time_limit, microsecs, read_kbd, do_display;
4538 Lisp_Object wait_for_cell;
4539 struct Lisp_Process *wait_proc;
4540 int just_wait_proc;
4541 {
4542 register int channel, nfds;
4543 SELECT_TYPE Available;
4544 #ifdef NON_BLOCKING_CONNECT
4545 SELECT_TYPE Connecting;
4546 int check_connect;
4547 #endif
4548 int check_delay, no_avail;
4549 int xerrno;
4550 Lisp_Object proc;
4551 EMACS_TIME timeout, end_time;
4552 int wait_channel = -1;
4553 int got_some_input = 0;
4554 int count = SPECPDL_INDEX ();
4555
4556 FD_ZERO (&Available);
4557 #ifdef NON_BLOCKING_CONNECT
4558 FD_ZERO (&Connecting);
4559 #endif
4560
4561 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4562 if (wait_proc != NULL)
4563 wait_channel = wait_proc->infd;
4564
4565 record_unwind_protect (wait_reading_process_output_unwind,
4566 make_number (waiting_for_user_input_p));
4567 waiting_for_user_input_p = read_kbd;
4568
4569 /* Since we may need to wait several times,
4570 compute the absolute time to return at. */
4571 if (time_limit || microsecs)
4572 {
4573 EMACS_GET_TIME (end_time);
4574 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4575 EMACS_ADD_TIME (end_time, end_time, timeout);
4576 }
4577
4578 while (1)
4579 {
4580 int timeout_reduced_for_timers = 0;
4581
4582 /* If calling from keyboard input, do not quit
4583 since we want to return C-g as an input character.
4584 Otherwise, do pending quit if requested. */
4585 if (read_kbd >= 0)
4586 QUIT;
4587 #ifdef SYNC_INPUT
4588 else
4589 {
4590 if (interrupt_input_pending)
4591 handle_async_input ();
4592 if (pending_atimers)
4593 do_pending_atimers ();
4594 }
4595 #endif
4596
4597 /* Exit now if the cell we're waiting for became non-nil. */
4598 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4599 break;
4600
4601 /* Compute time from now till when time limit is up */
4602 /* Exit if already run out */
4603 if (time_limit == -1)
4604 {
4605 /* -1 specified for timeout means
4606 gobble output available now
4607 but don't wait at all. */
4608
4609 EMACS_SET_SECS_USECS (timeout, 0, 0);
4610 }
4611 else if (time_limit || microsecs)
4612 {
4613 EMACS_GET_TIME (timeout);
4614 EMACS_SUB_TIME (timeout, end_time, timeout);
4615 if (EMACS_TIME_NEG_P (timeout))
4616 break;
4617 }
4618 else
4619 {
4620 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4621 }
4622
4623 /* Normally we run timers here.
4624 But not if wait_for_cell; in those cases,
4625 the wait is supposed to be short,
4626 and those callers cannot handle running arbitrary Lisp code here. */
4627 if (NILP (wait_for_cell)
4628 && just_wait_proc >= 0)
4629 {
4630 EMACS_TIME timer_delay;
4631
4632 do
4633 {
4634 int old_timers_run = timers_run;
4635 struct buffer *old_buffer = current_buffer;
4636 Lisp_Object old_window = selected_window;
4637
4638 timer_delay = timer_check (1);
4639
4640 /* If a timer has run, this might have changed buffers
4641 an alike. Make read_key_sequence aware of that. */
4642 if (timers_run != old_timers_run
4643 && (old_buffer != current_buffer
4644 || !EQ (old_window, selected_window))
4645 && waiting_for_user_input_p == -1)
4646 record_asynch_buffer_change ();
4647
4648 if (timers_run != old_timers_run && do_display)
4649 /* We must retry, since a timer may have requeued itself
4650 and that could alter the time_delay. */
4651 redisplay_preserve_echo_area (9);
4652 else
4653 break;
4654 }
4655 while (!detect_input_pending ());
4656
4657 /* If there is unread keyboard input, also return. */
4658 if (read_kbd != 0
4659 && requeued_events_pending_p ())
4660 break;
4661
4662 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4663 {
4664 EMACS_TIME difference;
4665 EMACS_SUB_TIME (difference, timer_delay, timeout);
4666 if (EMACS_TIME_NEG_P (difference))
4667 {
4668 timeout = timer_delay;
4669 timeout_reduced_for_timers = 1;
4670 }
4671 }
4672 /* If time_limit is -1, we are not going to wait at all. */
4673 else if (time_limit != -1)
4674 {
4675 /* This is so a breakpoint can be put here. */
4676 wait_reading_process_output_1 ();
4677 }
4678 }
4679
4680 /* Cause C-g and alarm signals to take immediate action,
4681 and cause input available signals to zero out timeout.
4682
4683 It is important that we do this before checking for process
4684 activity. If we get a SIGCHLD after the explicit checks for
4685 process activity, timeout is the only way we will know. */
4686 if (read_kbd < 0)
4687 set_waiting_for_input (&timeout);
4688
4689 /* If status of something has changed, and no input is
4690 available, notify the user of the change right away. After
4691 this explicit check, we'll let the SIGCHLD handler zap
4692 timeout to get our attention. When Emacs is run
4693 interactively, only do this with a nonzero DO_DISPLAY
4694 argument, because status_notify triggers redisplay. */
4695 if (update_tick != process_tick
4696 && (do_display || noninteractive))
4697 {
4698 SELECT_TYPE Atemp;
4699 #ifdef NON_BLOCKING_CONNECT
4700 SELECT_TYPE Ctemp;
4701 #endif
4702
4703 Atemp = input_wait_mask;
4704 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4705
4706 EMACS_SET_SECS_USECS (timeout, 0, 0);
4707 if ((select (max (max (max_process_desc, max_keyboard_desc),
4708 max_gpm_desc) + 1,
4709 &Atemp,
4710 #ifdef NON_BLOCKING_CONNECT
4711 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4712 #else
4713 (SELECT_TYPE *)0,
4714 #endif
4715 (SELECT_TYPE *)0, &timeout)
4716 <= 0))
4717 {
4718 /* It's okay for us to do this and then continue with
4719 the loop, since timeout has already been zeroed out. */
4720 clear_waiting_for_input ();
4721 status_notify (NULL);
4722 }
4723 }
4724
4725 /* Don't wait for output from a non-running process. Just
4726 read whatever data has already been received. */
4727 if (wait_proc && wait_proc->raw_status_new)
4728 update_status (wait_proc);
4729 if (wait_proc
4730 && ! EQ (wait_proc->status, Qrun)
4731 && ! EQ (wait_proc->status, Qconnect))
4732 {
4733 int nread, total_nread = 0;
4734
4735 clear_waiting_for_input ();
4736 XSETPROCESS (proc, wait_proc);
4737
4738 /* Read data from the process, until we exhaust it. */
4739 while (wait_proc->infd >= 0)
4740 {
4741 nread = read_process_output (proc, wait_proc->infd);
4742
4743 if (nread == 0)
4744 break;
4745
4746 if (0 < nread)
4747 {
4748 total_nread += nread;
4749 got_some_input = 1;
4750 }
4751 #ifdef EIO
4752 else if (nread == -1 && EIO == errno)
4753 break;
4754 #endif
4755 #ifdef EAGAIN
4756 else if (nread == -1 && EAGAIN == errno)
4757 break;
4758 #endif
4759 #ifdef EWOULDBLOCK
4760 else if (nread == -1 && EWOULDBLOCK == errno)
4761 break;
4762 #endif
4763 }
4764 if (total_nread > 0 && do_display)
4765 redisplay_preserve_echo_area (10);
4766
4767 break;
4768 }
4769
4770 /* Wait till there is something to do */
4771
4772 if (wait_proc && just_wait_proc)
4773 {
4774 if (wait_proc->infd < 0) /* Terminated */
4775 break;
4776 FD_SET (wait_proc->infd, &Available);
4777 check_delay = 0;
4778 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4779 }
4780 else if (!NILP (wait_for_cell))
4781 {
4782 Available = non_process_wait_mask;
4783 check_delay = 0;
4784 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4785 }
4786 else
4787 {
4788 if (! read_kbd)
4789 Available = non_keyboard_wait_mask;
4790 else
4791 Available = input_wait_mask;
4792 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4793 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4794 }
4795
4796 /* If frame size has changed or the window is newly mapped,
4797 redisplay now, before we start to wait. There is a race
4798 condition here; if a SIGIO arrives between now and the select
4799 and indicates that a frame is trashed, the select may block
4800 displaying a trashed screen. */
4801 if (frame_garbaged && do_display)
4802 {
4803 clear_waiting_for_input ();
4804 redisplay_preserve_echo_area (11);
4805 if (read_kbd < 0)
4806 set_waiting_for_input (&timeout);
4807 }
4808
4809 no_avail = 0;
4810 if (read_kbd && detect_input_pending ())
4811 {
4812 nfds = 0;
4813 no_avail = 1;
4814 }
4815 else
4816 {
4817 #ifdef NON_BLOCKING_CONNECT
4818 if (check_connect)
4819 Connecting = connect_wait_mask;
4820 #endif
4821
4822 #ifdef ADAPTIVE_READ_BUFFERING
4823 /* Set the timeout for adaptive read buffering if any
4824 process has non-zero read_output_skip and non-zero
4825 read_output_delay, and we are not reading output for a
4826 specific wait_channel. It is not executed if
4827 Vprocess_adaptive_read_buffering is nil. */
4828 if (process_output_skip && check_delay > 0)
4829 {
4830 int usecs = EMACS_USECS (timeout);
4831 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4832 usecs = READ_OUTPUT_DELAY_MAX;
4833 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4834 {
4835 proc = chan_process[channel];
4836 if (NILP (proc))
4837 continue;
4838 /* Find minimum non-zero read_output_delay among the
4839 processes with non-zero read_output_skip. */
4840 if (XPROCESS (proc)->read_output_delay > 0)
4841 {
4842 check_delay--;
4843 if (!XPROCESS (proc)->read_output_skip)
4844 continue;
4845 FD_CLR (channel, &Available);
4846 XPROCESS (proc)->read_output_skip = 0;
4847 if (XPROCESS (proc)->read_output_delay < usecs)
4848 usecs = XPROCESS (proc)->read_output_delay;
4849 }
4850 }
4851 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4852 process_output_skip = 0;
4853 }
4854 #endif
4855 #ifdef HAVE_NS
4856 nfds = ns_select
4857 #else
4858 nfds = select
4859 #endif
4860 (max (max (max_process_desc, max_keyboard_desc),
4861 max_gpm_desc) + 1,
4862 &Available,
4863 #ifdef NON_BLOCKING_CONNECT
4864 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4865 #else
4866 (SELECT_TYPE *)0,
4867 #endif
4868 (SELECT_TYPE *)0, &timeout);
4869 }
4870
4871 xerrno = errno;
4872
4873 /* Make C-g and alarm signals set flags again */
4874 clear_waiting_for_input ();
4875
4876 /* If we woke up due to SIGWINCH, actually change size now. */
4877 do_pending_window_change (0);
4878
4879 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4880 /* We wanted the full specified time, so return now. */
4881 break;
4882 if (nfds < 0)
4883 {
4884 if (xerrno == EINTR)
4885 no_avail = 1;
4886 else if (xerrno == EBADF)
4887 {
4888 #ifdef AIX
4889 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4890 the child's closure of the pts gives the parent a SIGHUP, and
4891 the ptc file descriptor is automatically closed,
4892 yielding EBADF here or at select() call above.
4893 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4894 in m/ibmrt-aix.h), and here we just ignore the select error.
4895 Cleanup occurs c/o status_notify after SIGCLD. */
4896 no_avail = 1; /* Cannot depend on values returned */
4897 #else
4898 abort ();
4899 #endif
4900 }
4901 else
4902 error ("select error: %s", emacs_strerror (xerrno));
4903 }
4904
4905 if (no_avail)
4906 {
4907 FD_ZERO (&Available);
4908 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4909 }
4910
4911 #if 0 /* When polling is used, interrupt_input is 0,
4912 so get_input_pending should read the input.
4913 So this should not be needed. */
4914 /* If we are using polling for input,
4915 and we see input available, make it get read now.
4916 Otherwise it might not actually get read for a second.
4917 And on hpux, since we turn off polling in wait_reading_process_output,
4918 it might never get read at all if we don't spend much time
4919 outside of wait_reading_process_output. */
4920 if (read_kbd && interrupt_input
4921 && keyboard_bit_set (&Available)
4922 && input_polling_used ())
4923 kill (getpid (), SIGALRM);
4924 #endif
4925
4926 /* Check for keyboard input */
4927 /* If there is any, return immediately
4928 to give it higher priority than subprocesses */
4929
4930 if (read_kbd != 0)
4931 {
4932 int old_timers_run = timers_run;
4933 struct buffer *old_buffer = current_buffer;
4934 Lisp_Object old_window = selected_window;
4935 int leave = 0;
4936
4937 if (detect_input_pending_run_timers (do_display))
4938 {
4939 swallow_events (do_display);
4940 if (detect_input_pending_run_timers (do_display))
4941 leave = 1;
4942 }
4943
4944 /* If a timer has run, this might have changed buffers
4945 an alike. Make read_key_sequence aware of that. */
4946 if (timers_run != old_timers_run
4947 && waiting_for_user_input_p == -1
4948 && (old_buffer != current_buffer
4949 || !EQ (old_window, selected_window)))
4950 record_asynch_buffer_change ();
4951
4952 if (leave)
4953 break;
4954 }
4955
4956 /* If there is unread keyboard input, also return. */
4957 if (read_kbd != 0
4958 && requeued_events_pending_p ())
4959 break;
4960
4961 /* If we are not checking for keyboard input now,
4962 do process events (but don't run any timers).
4963 This is so that X events will be processed.
4964 Otherwise they may have to wait until polling takes place.
4965 That would causes delays in pasting selections, for example.
4966
4967 (We used to do this only if wait_for_cell.) */
4968 if (read_kbd == 0 && detect_input_pending ())
4969 {
4970 swallow_events (do_display);
4971 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4972 if (detect_input_pending ())
4973 break;
4974 #endif
4975 }
4976
4977 /* Exit now if the cell we're waiting for became non-nil. */
4978 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4979 break;
4980
4981 #ifdef SIGIO
4982 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4983 go read it. This can happen with X on BSD after logging out.
4984 In that case, there really is no input and no SIGIO,
4985 but select says there is input. */
4986
4987 if (read_kbd && interrupt_input
4988 && keyboard_bit_set (&Available) && ! noninteractive)
4989 kill (getpid (), SIGIO);
4990 #endif
4991
4992 if (! wait_proc)
4993 got_some_input |= nfds > 0;
4994
4995 /* If checking input just got us a size-change event from X,
4996 obey it now if we should. */
4997 if (read_kbd || ! NILP (wait_for_cell))
4998 do_pending_window_change (0);
4999
5000 /* Check for data from a process. */
5001 if (no_avail || nfds == 0)
5002 continue;
5003
5004 /* Really FIRST_PROC_DESC should be 0 on Unix,
5005 but this is safer in the short run. */
5006 for (channel = 0; channel <= max_process_desc; channel++)
5007 {
5008 if (FD_ISSET (channel, &Available)
5009 && FD_ISSET (channel, &non_keyboard_wait_mask))
5010 {
5011 int nread;
5012
5013 /* If waiting for this channel, arrange to return as
5014 soon as no more input to be processed. No more
5015 waiting. */
5016 if (wait_channel == channel)
5017 {
5018 wait_channel = -1;
5019 time_limit = -1;
5020 got_some_input = 1;
5021 }
5022 proc = chan_process[channel];
5023 if (NILP (proc))
5024 continue;
5025
5026 /* If this is a server stream socket, accept connection. */
5027 if (EQ (XPROCESS (proc)->status, Qlisten))
5028 {
5029 server_accept_connection (proc, channel);
5030 continue;
5031 }
5032
5033 /* Read data from the process, starting with our
5034 buffered-ahead character if we have one. */
5035
5036 nread = read_process_output (proc, channel);
5037 if (nread > 0)
5038 {
5039 /* Since read_process_output can run a filter,
5040 which can call accept-process-output,
5041 don't try to read from any other processes
5042 before doing the select again. */
5043 FD_ZERO (&Available);
5044
5045 if (do_display)
5046 redisplay_preserve_echo_area (12);
5047 }
5048 #ifdef EWOULDBLOCK
5049 else if (nread == -1 && errno == EWOULDBLOCK)
5050 ;
5051 #endif
5052 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5053 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5054 #ifdef O_NONBLOCK
5055 else if (nread == -1 && errno == EAGAIN)
5056 ;
5057 #else
5058 #ifdef O_NDELAY
5059 else if (nread == -1 && errno == EAGAIN)
5060 ;
5061 /* Note that we cannot distinguish between no input
5062 available now and a closed pipe.
5063 With luck, a closed pipe will be accompanied by
5064 subprocess termination and SIGCHLD. */
5065 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5066 ;
5067 #endif /* O_NDELAY */
5068 #endif /* O_NONBLOCK */
5069 #ifdef HAVE_PTYS
5070 /* On some OSs with ptys, when the process on one end of
5071 a pty exits, the other end gets an error reading with
5072 errno = EIO instead of getting an EOF (0 bytes read).
5073 Therefore, if we get an error reading and errno =
5074 EIO, just continue, because the child process has
5075 exited and should clean itself up soon (e.g. when we
5076 get a SIGCHLD).
5077
5078 However, it has been known to happen that the SIGCHLD
5079 got lost. So raise the signal again just in case.
5080 It can't hurt. */
5081 else if (nread == -1 && errno == EIO)
5082 {
5083 /* Clear the descriptor now, so we only raise the signal once. */
5084 FD_CLR (channel, &input_wait_mask);
5085 FD_CLR (channel, &non_keyboard_wait_mask);
5086
5087 kill (getpid (), SIGCHLD);
5088 }
5089 #endif /* HAVE_PTYS */
5090 /* If we can detect process termination, don't consider the process
5091 gone just because its pipe is closed. */
5092 #ifdef SIGCHLD
5093 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5094 ;
5095 #endif
5096 else
5097 {
5098 /* Preserve status of processes already terminated. */
5099 XPROCESS (proc)->tick = ++process_tick;
5100 deactivate_process (proc);
5101 if (XPROCESS (proc)->raw_status_new)
5102 update_status (XPROCESS (proc));
5103 if (EQ (XPROCESS (proc)->status, Qrun))
5104 XPROCESS (proc)->status
5105 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5106 }
5107 }
5108 #ifdef NON_BLOCKING_CONNECT
5109 if (check_connect && FD_ISSET (channel, &Connecting)
5110 && FD_ISSET (channel, &connect_wait_mask))
5111 {
5112 struct Lisp_Process *p;
5113
5114 FD_CLR (channel, &connect_wait_mask);
5115 if (--num_pending_connects < 0)
5116 abort ();
5117
5118 proc = chan_process[channel];
5119 if (NILP (proc))
5120 continue;
5121
5122 p = XPROCESS (proc);
5123
5124 #ifdef GNU_LINUX
5125 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5126 So only use it on systems where it is known to work. */
5127 {
5128 int xlen = sizeof(xerrno);
5129 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5130 xerrno = errno;
5131 }
5132 #else
5133 {
5134 struct sockaddr pname;
5135 int pnamelen = sizeof(pname);
5136
5137 /* If connection failed, getpeername will fail. */
5138 xerrno = 0;
5139 if (getpeername(channel, &pname, &pnamelen) < 0)
5140 {
5141 /* Obtain connect failure code through error slippage. */
5142 char dummy;
5143 xerrno = errno;
5144 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
5145 xerrno = errno;
5146 }
5147 }
5148 #endif
5149 if (xerrno)
5150 {
5151 p->tick = ++process_tick;
5152 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5153 deactivate_process (proc);
5154 }
5155 else
5156 {
5157 p->status = Qrun;
5158 /* Execute the sentinel here. If we had relied on
5159 status_notify to do it later, it will read input
5160 from the process before calling the sentinel. */
5161 exec_sentinel (proc, build_string ("open\n"));
5162 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5163 {
5164 FD_SET (p->infd, &input_wait_mask);
5165 FD_SET (p->infd, &non_keyboard_wait_mask);
5166 }
5167 }
5168 }
5169 #endif /* NON_BLOCKING_CONNECT */
5170 } /* end for each file descriptor */
5171 } /* end while exit conditions not met */
5172
5173 unbind_to (count, Qnil);
5174
5175 /* If calling from keyboard input, do not quit
5176 since we want to return C-g as an input character.
5177 Otherwise, do pending quit if requested. */
5178 if (read_kbd >= 0)
5179 {
5180 /* Prevent input_pending from remaining set if we quit. */
5181 clear_input_pending ();
5182 QUIT;
5183 }
5184
5185 return got_some_input;
5186 }
5187 \f
5188 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5189
5190 static Lisp_Object
5191 read_process_output_call (fun_and_args)
5192 Lisp_Object fun_and_args;
5193 {
5194 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5195 }
5196
5197 static Lisp_Object
5198 read_process_output_error_handler (error)
5199 Lisp_Object error;
5200 {
5201 cmd_error_internal (error, "error in process filter: ");
5202 Vinhibit_quit = Qt;
5203 update_echo_area ();
5204 Fsleep_for (make_number (2), Qnil);
5205 return Qt;
5206 }
5207
5208 /* Read pending output from the process channel,
5209 starting with our buffered-ahead character if we have one.
5210 Yield number of decoded characters read.
5211
5212 This function reads at most 4096 characters.
5213 If you want to read all available subprocess output,
5214 you must call it repeatedly until it returns zero.
5215
5216 The characters read are decoded according to PROC's coding-system
5217 for decoding. */
5218
5219 static int
5220 read_process_output (proc, channel)
5221 Lisp_Object proc;
5222 register int channel;
5223 {
5224 register int nbytes;
5225 char *chars;
5226 register Lisp_Object outstream;
5227 register struct buffer *old = current_buffer;
5228 register struct Lisp_Process *p = XPROCESS (proc);
5229 register int opoint;
5230 struct coding_system *coding = proc_decode_coding_system[channel];
5231 int carryover = p->decoding_carryover;
5232 int readmax = 4096;
5233
5234 #ifdef VMS
5235 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
5236
5237 vs = get_vms_process_pointer (p->pid);
5238 if (vs)
5239 {
5240 if (!vs->iosb[0])
5241 return (0); /* Really weird if it does this */
5242 if (!(vs->iosb[0] & 1))
5243 return -1; /* I/O error */
5244 }
5245 else
5246 error ("Could not get VMS process pointer");
5247 chars = vs->inputBuffer;
5248 nbytes = clean_vms_buffer (chars, vs->iosb[1]);
5249 if (nbytes <= 0)
5250 {
5251 start_vms_process_read (vs); /* Crank up the next read on the process */
5252 return 1; /* Nothing worth printing, say we got 1 */
5253 }
5254 if (carryover > 0)
5255 {
5256 /* The data carried over in the previous decoding (which are at
5257 the tail of decoding buffer) should be prepended to the new
5258 data read to decode all together. */
5259 chars = (char *) alloca (nbytes + carryover);
5260 bcopy (SDATA (p->decoding_buf), buf, carryover);
5261 bcopy (vs->inputBuffer, chars + carryover, nbytes);
5262 }
5263 #else /* not VMS */
5264
5265 chars = (char *) alloca (carryover + readmax);
5266 if (carryover)
5267 /* See the comment above. */
5268 bcopy (SDATA (p->decoding_buf), chars, carryover);
5269
5270 #ifdef DATAGRAM_SOCKETS
5271 /* We have a working select, so proc_buffered_char is always -1. */
5272 if (DATAGRAM_CHAN_P (channel))
5273 {
5274 int len = datagram_address[channel].len;
5275 nbytes = recvfrom (channel, chars + carryover, readmax,
5276 0, datagram_address[channel].sa, &len);
5277 }
5278 else
5279 #endif
5280 if (proc_buffered_char[channel] < 0)
5281 {
5282 nbytes = emacs_read (channel, chars + carryover, readmax);
5283 #ifdef ADAPTIVE_READ_BUFFERING
5284 if (nbytes > 0 && p->adaptive_read_buffering)
5285 {
5286 int delay = p->read_output_delay;
5287 if (nbytes < 256)
5288 {
5289 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5290 {
5291 if (delay == 0)
5292 process_output_delay_count++;
5293 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5294 }
5295 }
5296 else if (delay > 0 && (nbytes == readmax))
5297 {
5298 delay -= READ_OUTPUT_DELAY_INCREMENT;
5299 if (delay == 0)
5300 process_output_delay_count--;
5301 }
5302 p->read_output_delay = delay;
5303 if (delay)
5304 {
5305 p->read_output_skip = 1;
5306 process_output_skip = 1;
5307 }
5308 }
5309 #endif
5310 }
5311 else
5312 {
5313 chars[carryover] = proc_buffered_char[channel];
5314 proc_buffered_char[channel] = -1;
5315 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5316 if (nbytes < 0)
5317 nbytes = 1;
5318 else
5319 nbytes = nbytes + 1;
5320 }
5321 #endif /* not VMS */
5322
5323 p->decoding_carryover = 0;
5324
5325 /* At this point, NBYTES holds number of bytes just received
5326 (including the one in proc_buffered_char[channel]). */
5327 if (nbytes <= 0)
5328 {
5329 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5330 return nbytes;
5331 coding->mode |= CODING_MODE_LAST_BLOCK;
5332 }
5333
5334 /* Now set NBYTES how many bytes we must decode. */
5335 nbytes += carryover;
5336
5337 /* Read and dispose of the process output. */
5338 outstream = p->filter;
5339 if (!NILP (outstream))
5340 {
5341 /* We inhibit quit here instead of just catching it so that
5342 hitting ^G when a filter happens to be running won't screw
5343 it up. */
5344 int count = SPECPDL_INDEX ();
5345 Lisp_Object odeactivate;
5346 Lisp_Object obuffer, okeymap;
5347 Lisp_Object text;
5348 int outer_running_asynch_code = running_asynch_code;
5349 int waiting = waiting_for_user_input_p;
5350
5351 /* No need to gcpro these, because all we do with them later
5352 is test them for EQness, and none of them should be a string. */
5353 odeactivate = Vdeactivate_mark;
5354 XSETBUFFER (obuffer, current_buffer);
5355 okeymap = current_buffer->keymap;
5356
5357 specbind (Qinhibit_quit, Qt);
5358 specbind (Qlast_nonmenu_event, Qt);
5359
5360 /* In case we get recursively called,
5361 and we already saved the match data nonrecursively,
5362 save the same match data in safely recursive fashion. */
5363 if (outer_running_asynch_code)
5364 {
5365 Lisp_Object tem;
5366 /* Don't clobber the CURRENT match data, either! */
5367 tem = Fmatch_data (Qnil, Qnil, Qnil);
5368 restore_search_regs ();
5369 record_unwind_save_match_data ();
5370 Fset_match_data (tem, Qt);
5371 }
5372
5373 /* For speed, if a search happens within this code,
5374 save the match data in a special nonrecursive fashion. */
5375 running_asynch_code = 1;
5376
5377 decode_coding_c_string (coding, chars, nbytes, Qt);
5378 text = coding->dst_object;
5379 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5380 /* A new coding system might be found. */
5381 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5382 {
5383 p->decode_coding_system = Vlast_coding_system_used;
5384
5385 /* Don't call setup_coding_system for
5386 proc_decode_coding_system[channel] here. It is done in
5387 detect_coding called via decode_coding above. */
5388
5389 /* If a coding system for encoding is not yet decided, we set
5390 it as the same as coding-system for decoding.
5391
5392 But, before doing that we must check if
5393 proc_encode_coding_system[p->outfd] surely points to a
5394 valid memory because p->outfd will be changed once EOF is
5395 sent to the process. */
5396 if (NILP (p->encode_coding_system)
5397 && proc_encode_coding_system[p->outfd])
5398 {
5399 p->encode_coding_system
5400 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5401 setup_coding_system (p->encode_coding_system,
5402 proc_encode_coding_system[p->outfd]);
5403 }
5404 }
5405
5406 if (coding->carryover_bytes > 0)
5407 {
5408 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5409 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5410 bcopy (coding->carryover, SDATA (p->decoding_buf),
5411 coding->carryover_bytes);
5412 p->decoding_carryover = coding->carryover_bytes;
5413 }
5414 if (SBYTES (text) > 0)
5415 internal_condition_case_1 (read_process_output_call,
5416 Fcons (outstream,
5417 Fcons (proc, Fcons (text, Qnil))),
5418 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5419 read_process_output_error_handler);
5420
5421 /* If we saved the match data nonrecursively, restore it now. */
5422 restore_search_regs ();
5423 running_asynch_code = outer_running_asynch_code;
5424
5425 /* Handling the process output should not deactivate the mark. */
5426 Vdeactivate_mark = odeactivate;
5427
5428 /* Restore waiting_for_user_input_p as it was
5429 when we were called, in case the filter clobbered it. */
5430 waiting_for_user_input_p = waiting;
5431
5432 #if 0 /* Call record_asynch_buffer_change unconditionally,
5433 because we might have changed minor modes or other things
5434 that affect key bindings. */
5435 if (! EQ (Fcurrent_buffer (), obuffer)
5436 || ! EQ (current_buffer->keymap, okeymap))
5437 #endif
5438 /* But do it only if the caller is actually going to read events.
5439 Otherwise there's no need to make him wake up, and it could
5440 cause trouble (for example it would make sit_for return). */
5441 if (waiting_for_user_input_p == -1)
5442 record_asynch_buffer_change ();
5443
5444 #ifdef VMS
5445 start_vms_process_read (vs);
5446 #endif
5447 unbind_to (count, Qnil);
5448 return nbytes;
5449 }
5450
5451 /* If no filter, write into buffer if it isn't dead. */
5452 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5453 {
5454 Lisp_Object old_read_only;
5455 int old_begv, old_zv;
5456 int old_begv_byte, old_zv_byte;
5457 Lisp_Object odeactivate;
5458 int before, before_byte;
5459 int opoint_byte;
5460 Lisp_Object text;
5461 struct buffer *b;
5462
5463 odeactivate = Vdeactivate_mark;
5464
5465 Fset_buffer (p->buffer);
5466 opoint = PT;
5467 opoint_byte = PT_BYTE;
5468 old_read_only = current_buffer->read_only;
5469 old_begv = BEGV;
5470 old_zv = ZV;
5471 old_begv_byte = BEGV_BYTE;
5472 old_zv_byte = ZV_BYTE;
5473
5474 current_buffer->read_only = Qnil;
5475
5476 /* Insert new output into buffer
5477 at the current end-of-output marker,
5478 thus preserving logical ordering of input and output. */
5479 if (XMARKER (p->mark)->buffer)
5480 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5481 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5482 ZV_BYTE));
5483 else
5484 SET_PT_BOTH (ZV, ZV_BYTE);
5485 before = PT;
5486 before_byte = PT_BYTE;
5487
5488 /* If the output marker is outside of the visible region, save
5489 the restriction and widen. */
5490 if (! (BEGV <= PT && PT <= ZV))
5491 Fwiden ();
5492
5493 decode_coding_c_string (coding, chars, nbytes, Qt);
5494 text = coding->dst_object;
5495 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5496 /* A new coding system might be found. See the comment in the
5497 similar code in the previous `if' block. */
5498 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5499 {
5500 p->decode_coding_system = Vlast_coding_system_used;
5501 if (NILP (p->encode_coding_system)
5502 && proc_encode_coding_system[p->outfd])
5503 {
5504 p->encode_coding_system
5505 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5506 setup_coding_system (p->encode_coding_system,
5507 proc_encode_coding_system[p->outfd]);
5508 }
5509 }
5510 if (coding->carryover_bytes > 0)
5511 {
5512 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5513 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5514 bcopy (coding->carryover, SDATA (p->decoding_buf),
5515 coding->carryover_bytes);
5516 p->decoding_carryover = coding->carryover_bytes;
5517 }
5518 /* Adjust the multibyteness of TEXT to that of the buffer. */
5519 if (NILP (current_buffer->enable_multibyte_characters)
5520 != ! STRING_MULTIBYTE (text))
5521 text = (STRING_MULTIBYTE (text)
5522 ? Fstring_as_unibyte (text)
5523 : Fstring_to_multibyte (text));
5524 /* Insert before markers in case we are inserting where
5525 the buffer's mark is, and the user's next command is Meta-y. */
5526 insert_from_string_before_markers (text, 0, 0,
5527 SCHARS (text), SBYTES (text), 0);
5528
5529 /* Make sure the process marker's position is valid when the
5530 process buffer is changed in the signal_after_change above.
5531 W3 is known to do that. */
5532 if (BUFFERP (p->buffer)
5533 && (b = XBUFFER (p->buffer), b != current_buffer))
5534 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5535 else
5536 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5537
5538 update_mode_lines++;
5539
5540 /* Make sure opoint and the old restrictions
5541 float ahead of any new text just as point would. */
5542 if (opoint >= before)
5543 {
5544 opoint += PT - before;
5545 opoint_byte += PT_BYTE - before_byte;
5546 }
5547 if (old_begv > before)
5548 {
5549 old_begv += PT - before;
5550 old_begv_byte += PT_BYTE - before_byte;
5551 }
5552 if (old_zv >= before)
5553 {
5554 old_zv += PT - before;
5555 old_zv_byte += PT_BYTE - before_byte;
5556 }
5557
5558 /* If the restriction isn't what it should be, set it. */
5559 if (old_begv != BEGV || old_zv != ZV)
5560 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5561
5562 /* Handling the process output should not deactivate the mark. */
5563 Vdeactivate_mark = odeactivate;
5564
5565 current_buffer->read_only = old_read_only;
5566 SET_PT_BOTH (opoint, opoint_byte);
5567 set_buffer_internal (old);
5568 }
5569 #ifdef VMS
5570 start_vms_process_read (vs);
5571 #endif
5572 return nbytes;
5573 }
5574
5575 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5576 0, 0, 0,
5577 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5578 This is intended for use by asynchronous process output filters and sentinels. */)
5579 ()
5580 {
5581 return (waiting_for_user_input_p ? Qt : Qnil);
5582 }
5583 \f
5584 /* Sending data to subprocess */
5585
5586 jmp_buf send_process_frame;
5587 Lisp_Object process_sent_to;
5588
5589 SIGTYPE
5590 send_process_trap ()
5591 {
5592 SIGNAL_THREAD_CHECK (SIGPIPE);
5593 sigunblock (sigmask (SIGPIPE));
5594 longjmp (send_process_frame, 1);
5595 }
5596
5597 /* Send some data to process PROC.
5598 BUF is the beginning of the data; LEN is the number of characters.
5599 OBJECT is the Lisp object that the data comes from. If OBJECT is
5600 nil or t, it means that the data comes from C string.
5601
5602 If OBJECT is not nil, the data is encoded by PROC's coding-system
5603 for encoding before it is sent.
5604
5605 This function can evaluate Lisp code and can garbage collect. */
5606
5607 static void
5608 send_process (proc, buf, len, object)
5609 volatile Lisp_Object proc;
5610 unsigned char *volatile buf;
5611 volatile int len;
5612 volatile Lisp_Object object;
5613 {
5614 /* Use volatile to protect variables from being clobbered by longjmp. */
5615 struct Lisp_Process *p = XPROCESS (proc);
5616 int rv;
5617 struct coding_system *coding;
5618 struct gcpro gcpro1;
5619 SIGTYPE (*volatile old_sigpipe) ();
5620
5621 GCPRO1 (object);
5622
5623 #ifdef VMS
5624 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
5625 #endif /* VMS */
5626
5627 if (p->raw_status_new)
5628 update_status (p);
5629 if (! EQ (p->status, Qrun))
5630 error ("Process %s not running", SDATA (p->name));
5631 if (p->outfd < 0)
5632 error ("Output file descriptor of %s is closed", SDATA (p->name));
5633
5634 coding = proc_encode_coding_system[p->outfd];
5635 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5636
5637 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5638 || (BUFFERP (object)
5639 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5640 || EQ (object, Qt))
5641 {
5642 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5643 /* The coding system for encoding was changed to raw-text
5644 because we sent a unibyte text previously. Now we are
5645 sending a multibyte text, thus we must encode it by the
5646 original coding system specified for the current process. */
5647 setup_coding_system (p->encode_coding_system, coding);
5648 coding->src_multibyte = 1;
5649 }
5650 else
5651 {
5652 /* For sending a unibyte text, character code conversion should
5653 not take place but EOL conversion should. So, setup raw-text
5654 or one of the subsidiary if we have not yet done it. */
5655 if (CODING_REQUIRE_ENCODING (coding))
5656 {
5657 if (CODING_REQUIRE_FLUSHING (coding))
5658 {
5659 /* But, before changing the coding, we must flush out data. */
5660 coding->mode |= CODING_MODE_LAST_BLOCK;
5661 send_process (proc, "", 0, Qt);
5662 coding->mode &= CODING_MODE_LAST_BLOCK;
5663 }
5664 setup_coding_system (raw_text_coding_system
5665 (Vlast_coding_system_used),
5666 coding);
5667 coding->src_multibyte = 0;
5668 }
5669 }
5670 coding->dst_multibyte = 0;
5671
5672 if (CODING_REQUIRE_ENCODING (coding))
5673 {
5674 coding->dst_object = Qt;
5675 if (BUFFERP (object))
5676 {
5677 int from_byte, from, to;
5678 int save_pt, save_pt_byte;
5679 struct buffer *cur = current_buffer;
5680
5681 set_buffer_internal (XBUFFER (object));
5682 save_pt = PT, save_pt_byte = PT_BYTE;
5683
5684 from_byte = PTR_BYTE_POS (buf);
5685 from = BYTE_TO_CHAR (from_byte);
5686 to = BYTE_TO_CHAR (from_byte + len);
5687 TEMP_SET_PT_BOTH (from, from_byte);
5688 encode_coding_object (coding, object, from, from_byte,
5689 to, from_byte + len, Qt);
5690 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5691 set_buffer_internal (cur);
5692 }
5693 else if (STRINGP (object))
5694 {
5695 encode_coding_string (coding, object, 1);
5696 }
5697 else
5698 {
5699 coding->dst_object = make_unibyte_string (buf, len);
5700 coding->produced = len;
5701 }
5702
5703 len = coding->produced;
5704 buf = SDATA (coding->dst_object);
5705 }
5706
5707 #ifdef VMS
5708 vs = get_vms_process_pointer (p->pid);
5709 if (vs == 0)
5710 error ("Could not find this process: %x", p->pid);
5711 else if (write_to_vms_process (vs, buf, len))
5712 ;
5713 #else /* not VMS */
5714
5715 if (pty_max_bytes == 0)
5716 {
5717 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5718 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5719 if (pty_max_bytes < 0)
5720 pty_max_bytes = 250;
5721 #else
5722 pty_max_bytes = 250;
5723 #endif
5724 /* Deduct one, to leave space for the eof. */
5725 pty_max_bytes--;
5726 }
5727
5728 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5729 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5730 when returning with longjmp despite being declared volatile. */
5731 if (!setjmp (send_process_frame))
5732 {
5733 process_sent_to = proc;
5734 while (len > 0)
5735 {
5736 int this = len;
5737
5738 /* Decide how much data we can send in one batch.
5739 Long lines need to be split into multiple batches. */
5740 if (p->pty_flag)
5741 {
5742 /* Starting this at zero is always correct when not the first
5743 iteration because the previous iteration ended by sending C-d.
5744 It may not be correct for the first iteration
5745 if a partial line was sent in a separate send_process call.
5746 If that proves worth handling, we need to save linepos
5747 in the process object. */
5748 int linepos = 0;
5749 unsigned char *ptr = (unsigned char *) buf;
5750 unsigned char *end = (unsigned char *) buf + len;
5751
5752 /* Scan through this text for a line that is too long. */
5753 while (ptr != end && linepos < pty_max_bytes)
5754 {
5755 if (*ptr == '\n')
5756 linepos = 0;
5757 else
5758 linepos++;
5759 ptr++;
5760 }
5761 /* If we found one, break the line there
5762 and put in a C-d to force the buffer through. */
5763 this = ptr - buf;
5764 }
5765
5766 /* Send this batch, using one or more write calls. */
5767 while (this > 0)
5768 {
5769 int outfd = p->outfd;
5770 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5771 #ifdef DATAGRAM_SOCKETS
5772 if (DATAGRAM_CHAN_P (outfd))
5773 {
5774 rv = sendto (outfd, (char *) buf, this,
5775 0, datagram_address[outfd].sa,
5776 datagram_address[outfd].len);
5777 if (rv < 0 && errno == EMSGSIZE)
5778 {
5779 signal (SIGPIPE, old_sigpipe);
5780 report_file_error ("sending datagram",
5781 Fcons (proc, Qnil));
5782 }
5783 }
5784 else
5785 #endif
5786 {
5787 rv = emacs_write (outfd, (char *) buf, this);
5788 #ifdef ADAPTIVE_READ_BUFFERING
5789 if (p->read_output_delay > 0
5790 && p->adaptive_read_buffering == 1)
5791 {
5792 p->read_output_delay = 0;
5793 process_output_delay_count--;
5794 p->read_output_skip = 0;
5795 }
5796 #endif
5797 }
5798 signal (SIGPIPE, old_sigpipe);
5799
5800 if (rv < 0)
5801 {
5802 if (0
5803 #ifdef EWOULDBLOCK
5804 || errno == EWOULDBLOCK
5805 #endif
5806 #ifdef EAGAIN
5807 || errno == EAGAIN
5808 #endif
5809 )
5810 /* Buffer is full. Wait, accepting input;
5811 that may allow the program
5812 to finish doing output and read more. */
5813 {
5814 int offset = 0;
5815
5816 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5817 /* A gross hack to work around a bug in FreeBSD.
5818 In the following sequence, read(2) returns
5819 bogus data:
5820
5821 write(2) 1022 bytes
5822 write(2) 954 bytes, get EAGAIN
5823 read(2) 1024 bytes in process_read_output
5824 read(2) 11 bytes in process_read_output
5825
5826 That is, read(2) returns more bytes than have
5827 ever been written successfully. The 1033 bytes
5828 read are the 1022 bytes written successfully
5829 after processing (for example with CRs added if
5830 the terminal is set up that way which it is
5831 here). The same bytes will be seen again in a
5832 later read(2), without the CRs. */
5833
5834 if (errno == EAGAIN)
5835 {
5836 int flags = FWRITE;
5837 ioctl (p->outfd, TIOCFLUSH, &flags);
5838 }
5839 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5840
5841 /* Running filters might relocate buffers or strings.
5842 Arrange to relocate BUF. */
5843 if (BUFFERP (object))
5844 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5845 else if (STRINGP (object))
5846 offset = buf - SDATA (object);
5847
5848 #ifdef EMACS_HAS_USECS
5849 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5850 #else
5851 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5852 #endif
5853
5854 if (BUFFERP (object))
5855 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5856 else if (STRINGP (object))
5857 buf = offset + SDATA (object);
5858
5859 rv = 0;
5860 }
5861 else
5862 /* This is a real error. */
5863 report_file_error ("writing to process", Fcons (proc, Qnil));
5864 }
5865 buf += rv;
5866 len -= rv;
5867 this -= rv;
5868 }
5869
5870 /* If we sent just part of the string, put in an EOF (C-d)
5871 to force it through, before we send the rest. */
5872 if (len > 0)
5873 Fprocess_send_eof (proc);
5874 }
5875 }
5876 #endif /* not VMS */
5877 else
5878 {
5879 signal (SIGPIPE, old_sigpipe);
5880 #ifndef VMS
5881 proc = process_sent_to;
5882 p = XPROCESS (proc);
5883 #endif
5884 p->raw_status_new = 0;
5885 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5886 p->tick = ++process_tick;
5887 deactivate_process (proc);
5888 #ifdef VMS
5889 error ("Error writing to process %s; closed it", SDATA (p->name));
5890 #else
5891 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5892 #endif
5893 }
5894
5895 UNGCPRO;
5896 }
5897
5898 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5899 3, 3, 0,
5900 doc: /* Send current contents of region as input to PROCESS.
5901 PROCESS may be a process, a buffer, the name of a process or buffer, or
5902 nil, indicating the current buffer's process.
5903 Called from program, takes three arguments, PROCESS, START and END.
5904 If the region is more than 500 characters long,
5905 it is sent in several bunches. This may happen even for shorter regions.
5906 Output from processes can arrive in between bunches. */)
5907 (process, start, end)
5908 Lisp_Object process, start, end;
5909 {
5910 Lisp_Object proc;
5911 int start1, end1;
5912
5913 proc = get_process (process);
5914 validate_region (&start, &end);
5915
5916 if (XINT (start) < GPT && XINT (end) > GPT)
5917 move_gap (XINT (start));
5918
5919 start1 = CHAR_TO_BYTE (XINT (start));
5920 end1 = CHAR_TO_BYTE (XINT (end));
5921 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5922 Fcurrent_buffer ());
5923
5924 return Qnil;
5925 }
5926
5927 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5928 2, 2, 0,
5929 doc: /* Send PROCESS the contents of STRING as input.
5930 PROCESS may be a process, a buffer, the name of a process or buffer, or
5931 nil, indicating the current buffer's process.
5932 If STRING is more than 500 characters long,
5933 it is sent in several bunches. This may happen even for shorter strings.
5934 Output from processes can arrive in between bunches. */)
5935 (process, string)
5936 Lisp_Object process, string;
5937 {
5938 Lisp_Object proc;
5939 CHECK_STRING (string);
5940 proc = get_process (process);
5941 send_process (proc, SDATA (string),
5942 SBYTES (string), string);
5943 return Qnil;
5944 }
5945 \f
5946 /* Return the foreground process group for the tty/pty that
5947 the process P uses. */
5948 static int
5949 emacs_get_tty_pgrp (p)
5950 struct Lisp_Process *p;
5951 {
5952 int gid = -1;
5953
5954 #ifdef TIOCGPGRP
5955 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5956 {
5957 int fd;
5958 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5959 master side. Try the slave side. */
5960 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5961
5962 if (fd != -1)
5963 {
5964 ioctl (fd, TIOCGPGRP, &gid);
5965 emacs_close (fd);
5966 }
5967 }
5968 #endif /* defined (TIOCGPGRP ) */
5969
5970 return gid;
5971 }
5972
5973 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5974 Sprocess_running_child_p, 0, 1, 0,
5975 doc: /* Return t if PROCESS has given the terminal to a child.
5976 If the operating system does not make it possible to find out,
5977 return t unconditionally. */)
5978 (process)
5979 Lisp_Object process;
5980 {
5981 /* Initialize in case ioctl doesn't exist or gives an error,
5982 in a way that will cause returning t. */
5983 int gid;
5984 Lisp_Object proc;
5985 struct Lisp_Process *p;
5986
5987 proc = get_process (process);
5988 p = XPROCESS (proc);
5989
5990 if (!EQ (p->type, Qreal))
5991 error ("Process %s is not a subprocess",
5992 SDATA (p->name));
5993 if (p->infd < 0)
5994 error ("Process %s is not active",
5995 SDATA (p->name));
5996
5997 gid = emacs_get_tty_pgrp (p);
5998
5999 if (gid == p->pid)
6000 return Qnil;
6001 return Qt;
6002 }
6003 \f
6004 /* send a signal number SIGNO to PROCESS.
6005 If CURRENT_GROUP is t, that means send to the process group
6006 that currently owns the terminal being used to communicate with PROCESS.
6007 This is used for various commands in shell mode.
6008 If CURRENT_GROUP is lambda, that means send to the process group
6009 that currently owns the terminal, but only if it is NOT the shell itself.
6010
6011 If NOMSG is zero, insert signal-announcements into process's buffers
6012 right away.
6013
6014 If we can, we try to signal PROCESS by sending control characters
6015 down the pty. This allows us to signal inferiors who have changed
6016 their uid, for which killpg would return an EPERM error. */
6017
6018 static void
6019 process_send_signal (process, signo, current_group, nomsg)
6020 Lisp_Object process;
6021 int signo;
6022 Lisp_Object current_group;
6023 int nomsg;
6024 {
6025 Lisp_Object proc;
6026 register struct Lisp_Process *p;
6027 int gid;
6028 int no_pgrp = 0;
6029
6030 proc = get_process (process);
6031 p = XPROCESS (proc);
6032
6033 if (!EQ (p->type, Qreal))
6034 error ("Process %s is not a subprocess",
6035 SDATA (p->name));
6036 if (p->infd < 0)
6037 error ("Process %s is not active",
6038 SDATA (p->name));
6039
6040 if (!p->pty_flag)
6041 current_group = Qnil;
6042
6043 /* If we are using pgrps, get a pgrp number and make it negative. */
6044 if (NILP (current_group))
6045 /* Send the signal to the shell's process group. */
6046 gid = p->pid;
6047 else
6048 {
6049 #ifdef SIGNALS_VIA_CHARACTERS
6050 /* If possible, send signals to the entire pgrp
6051 by sending an input character to it. */
6052
6053 /* TERMIOS is the latest and bestest, and seems most likely to
6054 work. If the system has it, use it. */
6055 #ifdef HAVE_TERMIOS
6056 struct termios t;
6057 cc_t *sig_char = NULL;
6058
6059 tcgetattr (p->infd, &t);
6060
6061 switch (signo)
6062 {
6063 case SIGINT:
6064 sig_char = &t.c_cc[VINTR];
6065 break;
6066
6067 case SIGQUIT:
6068 sig_char = &t.c_cc[VQUIT];
6069 break;
6070
6071 case SIGTSTP:
6072 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6073 sig_char = &t.c_cc[VSWTCH];
6074 #else
6075 sig_char = &t.c_cc[VSUSP];
6076 #endif
6077 break;
6078 }
6079
6080 if (sig_char && *sig_char != CDISABLE)
6081 {
6082 send_process (proc, sig_char, 1, Qnil);
6083 return;
6084 }
6085 /* If we can't send the signal with a character,
6086 fall through and send it another way. */
6087 #else /* ! HAVE_TERMIOS */
6088
6089 /* On Berkeley descendants, the following IOCTL's retrieve the
6090 current control characters. */
6091 #if defined (TIOCGLTC) && defined (TIOCGETC)
6092
6093 struct tchars c;
6094 struct ltchars lc;
6095
6096 switch (signo)
6097 {
6098 case SIGINT:
6099 ioctl (p->infd, TIOCGETC, &c);
6100 send_process (proc, &c.t_intrc, 1, Qnil);
6101 return;
6102 case SIGQUIT:
6103 ioctl (p->infd, TIOCGETC, &c);
6104 send_process (proc, &c.t_quitc, 1, Qnil);
6105 return;
6106 #ifdef SIGTSTP
6107 case SIGTSTP:
6108 ioctl (p->infd, TIOCGLTC, &lc);
6109 send_process (proc, &lc.t_suspc, 1, Qnil);
6110 return;
6111 #endif /* ! defined (SIGTSTP) */
6112 }
6113
6114 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6115
6116 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6117 characters. */
6118 #ifdef TCGETA
6119 struct termio t;
6120 switch (signo)
6121 {
6122 case SIGINT:
6123 ioctl (p->infd, TCGETA, &t);
6124 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6125 return;
6126 case SIGQUIT:
6127 ioctl (p->infd, TCGETA, &t);
6128 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6129 return;
6130 #ifdef SIGTSTP
6131 case SIGTSTP:
6132 ioctl (p->infd, TCGETA, &t);
6133 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6134 return;
6135 #endif /* ! defined (SIGTSTP) */
6136 }
6137 #else /* ! defined (TCGETA) */
6138 Your configuration files are messed up.
6139 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6140 you'd better be using one of the alternatives above! */
6141 #endif /* ! defined (TCGETA) */
6142 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6143 /* In this case, the code above should alway return. */
6144 abort ();
6145 #endif /* ! defined HAVE_TERMIOS */
6146
6147 /* The code above may fall through if it can't
6148 handle the signal. */
6149 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6150
6151 #ifdef TIOCGPGRP
6152 /* Get the current pgrp using the tty itself, if we have that.
6153 Otherwise, use the pty to get the pgrp.
6154 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6155 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6156 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6157 His patch indicates that if TIOCGPGRP returns an error, then
6158 we should just assume that p->pid is also the process group id. */
6159
6160 gid = emacs_get_tty_pgrp (p);
6161
6162 if (gid == -1)
6163 /* If we can't get the information, assume
6164 the shell owns the tty. */
6165 gid = p->pid;
6166
6167 /* It is not clear whether anything really can set GID to -1.
6168 Perhaps on some system one of those ioctls can or could do so.
6169 Or perhaps this is vestigial. */
6170 if (gid == -1)
6171 no_pgrp = 1;
6172 #else /* ! defined (TIOCGPGRP ) */
6173 /* Can't select pgrps on this system, so we know that
6174 the child itself heads the pgrp. */
6175 gid = p->pid;
6176 #endif /* ! defined (TIOCGPGRP ) */
6177
6178 /* If current_group is lambda, and the shell owns the terminal,
6179 don't send any signal. */
6180 if (EQ (current_group, Qlambda) && gid == p->pid)
6181 return;
6182 }
6183
6184 switch (signo)
6185 {
6186 #ifdef SIGCONT
6187 case SIGCONT:
6188 p->raw_status_new = 0;
6189 p->status = Qrun;
6190 p->tick = ++process_tick;
6191 if (!nomsg)
6192 status_notify (NULL);
6193 break;
6194 #endif /* ! defined (SIGCONT) */
6195 case SIGINT:
6196 #ifdef VMS
6197 send_process (proc, "\003", 1, Qnil); /* ^C */
6198 goto whoosh;
6199 #endif
6200 case SIGQUIT:
6201 #ifdef VMS
6202 send_process (proc, "\031", 1, Qnil); /* ^Y */
6203 goto whoosh;
6204 #endif
6205 case SIGKILL:
6206 #ifdef VMS
6207 sys$forcex (&(p->pid), 0, 1);
6208 whoosh:
6209 #endif
6210 flush_pending_output (p->infd);
6211 break;
6212 }
6213
6214 /* If we don't have process groups, send the signal to the immediate
6215 subprocess. That isn't really right, but it's better than any
6216 obvious alternative. */
6217 if (no_pgrp)
6218 {
6219 kill (p->pid, signo);
6220 return;
6221 }
6222
6223 /* gid may be a pid, or minus a pgrp's number */
6224 #ifdef TIOCSIGSEND
6225 if (!NILP (current_group))
6226 {
6227 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6228 EMACS_KILLPG (gid, signo);
6229 }
6230 else
6231 {
6232 gid = - p->pid;
6233 kill (gid, signo);
6234 }
6235 #else /* ! defined (TIOCSIGSEND) */
6236 EMACS_KILLPG (gid, signo);
6237 #endif /* ! defined (TIOCSIGSEND) */
6238 }
6239
6240 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6241 doc: /* Interrupt process PROCESS.
6242 PROCESS may be a process, a buffer, or the name of a process or buffer.
6243 No arg or nil means current buffer's process.
6244 Second arg CURRENT-GROUP non-nil means send signal to
6245 the current process-group of the process's controlling terminal
6246 rather than to the process's own process group.
6247 If the process is a shell, this means interrupt current subjob
6248 rather than the shell.
6249
6250 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6251 don't send the signal. */)
6252 (process, current_group)
6253 Lisp_Object process, current_group;
6254 {
6255 process_send_signal (process, SIGINT, current_group, 0);
6256 return process;
6257 }
6258
6259 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6260 doc: /* Kill process PROCESS. May be process or name of one.
6261 See function `interrupt-process' for more details on usage. */)
6262 (process, current_group)
6263 Lisp_Object process, current_group;
6264 {
6265 process_send_signal (process, SIGKILL, current_group, 0);
6266 return process;
6267 }
6268
6269 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6270 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6271 See function `interrupt-process' for more details on usage. */)
6272 (process, current_group)
6273 Lisp_Object process, current_group;
6274 {
6275 process_send_signal (process, SIGQUIT, current_group, 0);
6276 return process;
6277 }
6278
6279 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6280 doc: /* Stop process PROCESS. May be process or name of one.
6281 See function `interrupt-process' for more details on usage.
6282 If PROCESS is a network or serial process, inhibit handling of incoming
6283 traffic. */)
6284 (process, current_group)
6285 Lisp_Object process, current_group;
6286 {
6287 #ifdef HAVE_SOCKETS
6288 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6289 {
6290 struct Lisp_Process *p;
6291
6292 p = XPROCESS (process);
6293 if (NILP (p->command)
6294 && p->infd >= 0)
6295 {
6296 FD_CLR (p->infd, &input_wait_mask);
6297 FD_CLR (p->infd, &non_keyboard_wait_mask);
6298 }
6299 p->command = Qt;
6300 return process;
6301 }
6302 #endif
6303 #ifndef SIGTSTP
6304 error ("No SIGTSTP support");
6305 #else
6306 process_send_signal (process, SIGTSTP, current_group, 0);
6307 #endif
6308 return process;
6309 }
6310
6311 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6312 doc: /* Continue process PROCESS. May be process or name of one.
6313 See function `interrupt-process' for more details on usage.
6314 If PROCESS is a network or serial process, resume handling of incoming
6315 traffic. */)
6316 (process, current_group)
6317 Lisp_Object process, current_group;
6318 {
6319 #ifdef HAVE_SOCKETS
6320 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6321 {
6322 struct Lisp_Process *p;
6323
6324 p = XPROCESS (process);
6325 if (EQ (p->command, Qt)
6326 && p->infd >= 0
6327 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6328 {
6329 FD_SET (p->infd, &input_wait_mask);
6330 FD_SET (p->infd, &non_keyboard_wait_mask);
6331 #ifdef WINDOWSNT
6332 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6333 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6334 #endif
6335 #ifdef HAVE_TERMIOS
6336 tcflush (p->infd, TCIFLUSH);
6337 #endif
6338 }
6339 p->command = Qnil;
6340 return process;
6341 }
6342 #endif
6343 #ifdef SIGCONT
6344 process_send_signal (process, SIGCONT, current_group, 0);
6345 #else
6346 error ("No SIGCONT support");
6347 #endif
6348 return process;
6349 }
6350
6351 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6352 2, 2, "sProcess (name or number): \nnSignal code: ",
6353 doc: /* Send PROCESS the signal with code SIGCODE.
6354 PROCESS may also be a number specifying the process id of the
6355 process to signal; in this case, the process need not be a child of
6356 this Emacs.
6357 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6358 (process, sigcode)
6359 Lisp_Object process, sigcode;
6360 {
6361 pid_t pid;
6362
6363 if (INTEGERP (process))
6364 {
6365 pid = XINT (process);
6366 goto got_it;
6367 }
6368
6369 if (FLOATP (process))
6370 {
6371 pid = (pid_t) XFLOAT_DATA (process);
6372 goto got_it;
6373 }
6374
6375 if (STRINGP (process))
6376 {
6377 Lisp_Object tem;
6378 if (tem = Fget_process (process), NILP (tem))
6379 {
6380 pid = XINT (Fstring_to_number (process, make_number (10)));
6381 if (pid > 0)
6382 goto got_it;
6383 }
6384 process = tem;
6385 }
6386 else
6387 process = get_process (process);
6388
6389 if (NILP (process))
6390 return process;
6391
6392 CHECK_PROCESS (process);
6393 pid = XPROCESS (process)->pid;
6394 if (pid <= 0)
6395 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6396
6397 got_it:
6398
6399 #define parse_signal(NAME, VALUE) \
6400 else if (!xstrcasecmp (name, NAME)) \
6401 XSETINT (sigcode, VALUE)
6402
6403 if (INTEGERP (sigcode))
6404 ;
6405 else
6406 {
6407 unsigned char *name;
6408
6409 CHECK_SYMBOL (sigcode);
6410 name = SDATA (SYMBOL_NAME (sigcode));
6411
6412 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6413 name += 3;
6414
6415 if (0)
6416 ;
6417 #ifdef SIGUSR1
6418 parse_signal ("usr1", SIGUSR1);
6419 #endif
6420 #ifdef SIGUSR2
6421 parse_signal ("usr2", SIGUSR2);
6422 #endif
6423 #ifdef SIGTERM
6424 parse_signal ("term", SIGTERM);
6425 #endif
6426 #ifdef SIGHUP
6427 parse_signal ("hup", SIGHUP);
6428 #endif
6429 #ifdef SIGINT
6430 parse_signal ("int", SIGINT);
6431 #endif
6432 #ifdef SIGQUIT
6433 parse_signal ("quit", SIGQUIT);
6434 #endif
6435 #ifdef SIGILL
6436 parse_signal ("ill", SIGILL);
6437 #endif
6438 #ifdef SIGABRT
6439 parse_signal ("abrt", SIGABRT);
6440 #endif
6441 #ifdef SIGEMT
6442 parse_signal ("emt", SIGEMT);
6443 #endif
6444 #ifdef SIGKILL
6445 parse_signal ("kill", SIGKILL);
6446 #endif
6447 #ifdef SIGFPE
6448 parse_signal ("fpe", SIGFPE);
6449 #endif
6450 #ifdef SIGBUS
6451 parse_signal ("bus", SIGBUS);
6452 #endif
6453 #ifdef SIGSEGV
6454 parse_signal ("segv", SIGSEGV);
6455 #endif
6456 #ifdef SIGSYS
6457 parse_signal ("sys", SIGSYS);
6458 #endif
6459 #ifdef SIGPIPE
6460 parse_signal ("pipe", SIGPIPE);
6461 #endif
6462 #ifdef SIGALRM
6463 parse_signal ("alrm", SIGALRM);
6464 #endif
6465 #ifdef SIGURG
6466 parse_signal ("urg", SIGURG);
6467 #endif
6468 #ifdef SIGSTOP
6469 parse_signal ("stop", SIGSTOP);
6470 #endif
6471 #ifdef SIGTSTP
6472 parse_signal ("tstp", SIGTSTP);
6473 #endif
6474 #ifdef SIGCONT
6475 parse_signal ("cont", SIGCONT);
6476 #endif
6477 #ifdef SIGCHLD
6478 parse_signal ("chld", SIGCHLD);
6479 #endif
6480 #ifdef SIGTTIN
6481 parse_signal ("ttin", SIGTTIN);
6482 #endif
6483 #ifdef SIGTTOU
6484 parse_signal ("ttou", SIGTTOU);
6485 #endif
6486 #ifdef SIGIO
6487 parse_signal ("io", SIGIO);
6488 #endif
6489 #ifdef SIGXCPU
6490 parse_signal ("xcpu", SIGXCPU);
6491 #endif
6492 #ifdef SIGXFSZ
6493 parse_signal ("xfsz", SIGXFSZ);
6494 #endif
6495 #ifdef SIGVTALRM
6496 parse_signal ("vtalrm", SIGVTALRM);
6497 #endif
6498 #ifdef SIGPROF
6499 parse_signal ("prof", SIGPROF);
6500 #endif
6501 #ifdef SIGWINCH
6502 parse_signal ("winch", SIGWINCH);
6503 #endif
6504 #ifdef SIGINFO
6505 parse_signal ("info", SIGINFO);
6506 #endif
6507 else
6508 error ("Undefined signal name %s", name);
6509 }
6510
6511 #undef parse_signal
6512
6513 return make_number (kill (pid, XINT (sigcode)));
6514 }
6515
6516 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6517 doc: /* Make PROCESS see end-of-file in its input.
6518 EOF comes after any text already sent to it.
6519 PROCESS may be a process, a buffer, the name of a process or buffer, or
6520 nil, indicating the current buffer's process.
6521 If PROCESS is a network connection, or is a process communicating
6522 through a pipe (as opposed to a pty), then you cannot send any more
6523 text to PROCESS after you call this function.
6524 If PROCESS is a serial process, wait until all output written to the
6525 process has been transmitted to the serial port. */)
6526 (process)
6527 Lisp_Object process;
6528 {
6529 Lisp_Object proc;
6530 struct coding_system *coding;
6531
6532 if (DATAGRAM_CONN_P (process))
6533 return process;
6534
6535 proc = get_process (process);
6536 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6537
6538 /* Make sure the process is really alive. */
6539 if (XPROCESS (proc)->raw_status_new)
6540 update_status (XPROCESS (proc));
6541 if (! EQ (XPROCESS (proc)->status, Qrun))
6542 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6543
6544 if (CODING_REQUIRE_FLUSHING (coding))
6545 {
6546 coding->mode |= CODING_MODE_LAST_BLOCK;
6547 send_process (proc, "", 0, Qnil);
6548 }
6549
6550 #ifdef VMS
6551 send_process (proc, "\032", 1, Qnil); /* ^z */
6552 #else
6553 if (XPROCESS (proc)->pty_flag)
6554 send_process (proc, "\004", 1, Qnil);
6555 else if (EQ (XPROCESS (proc)->type, Qserial))
6556 {
6557 #ifdef HAVE_TERMIOS
6558 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6559 error ("tcdrain() failed: %s", emacs_strerror (errno));
6560 #endif
6561 /* Do nothing on Windows because writes are blocking. */
6562 }
6563 else
6564 {
6565 int old_outfd, new_outfd;
6566
6567 #ifdef HAVE_SHUTDOWN
6568 /* If this is a network connection, or socketpair is used
6569 for communication with the subprocess, call shutdown to cause EOF.
6570 (In some old system, shutdown to socketpair doesn't work.
6571 Then we just can't win.) */
6572 if (EQ (XPROCESS (proc)->type, Qnetwork)
6573 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6574 shutdown (XPROCESS (proc)->outfd, 1);
6575 /* In case of socketpair, outfd == infd, so don't close it. */
6576 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6577 emacs_close (XPROCESS (proc)->outfd);
6578 #else /* not HAVE_SHUTDOWN */
6579 emacs_close (XPROCESS (proc)->outfd);
6580 #endif /* not HAVE_SHUTDOWN */
6581 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6582 if (new_outfd < 0)
6583 abort ();
6584 old_outfd = XPROCESS (proc)->outfd;
6585
6586 if (!proc_encode_coding_system[new_outfd])
6587 proc_encode_coding_system[new_outfd]
6588 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6589 bcopy (proc_encode_coding_system[old_outfd],
6590 proc_encode_coding_system[new_outfd],
6591 sizeof (struct coding_system));
6592 bzero (proc_encode_coding_system[old_outfd],
6593 sizeof (struct coding_system));
6594
6595 XPROCESS (proc)->outfd = new_outfd;
6596 }
6597 #endif /* VMS */
6598 return process;
6599 }
6600
6601 /* Kill all processes associated with `buffer'.
6602 If `buffer' is nil, kill all processes */
6603
6604 void
6605 kill_buffer_processes (buffer)
6606 Lisp_Object buffer;
6607 {
6608 Lisp_Object tail, proc;
6609
6610 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6611 {
6612 proc = XCDR (XCAR (tail));
6613 if (PROCESSP (proc)
6614 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6615 {
6616 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6617 Fdelete_process (proc);
6618 else if (XPROCESS (proc)->infd >= 0)
6619 process_send_signal (proc, SIGHUP, Qnil, 1);
6620 }
6621 }
6622 }
6623 \f
6624 /* On receipt of a signal that a child status has changed, loop asking
6625 about children with changed statuses until the system says there
6626 are no more.
6627
6628 All we do is change the status; we do not run sentinels or print
6629 notifications. That is saved for the next time keyboard input is
6630 done, in order to avoid timing errors.
6631
6632 ** WARNING: this can be called during garbage collection.
6633 Therefore, it must not be fooled by the presence of mark bits in
6634 Lisp objects.
6635
6636 ** USG WARNING: Although it is not obvious from the documentation
6637 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6638 signal() before executing at least one wait(), otherwise the
6639 handler will be called again, resulting in an infinite loop. The
6640 relevant portion of the documentation reads "SIGCLD signals will be
6641 queued and the signal-catching function will be continually
6642 reentered until the queue is empty". Invoking signal() causes the
6643 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6644 Inc.
6645
6646 ** Malloc WARNING: This should never call malloc either directly or
6647 indirectly; if it does, that is a bug */
6648
6649 #ifdef SIGCHLD
6650 SIGTYPE
6651 sigchld_handler (signo)
6652 int signo;
6653 {
6654 int old_errno = errno;
6655 Lisp_Object proc;
6656 register struct Lisp_Process *p;
6657 extern EMACS_TIME *input_available_clear_time;
6658
6659 SIGNAL_THREAD_CHECK (signo);
6660
6661 while (1)
6662 {
6663 pid_t pid;
6664 int w;
6665 Lisp_Object tail;
6666
6667 #ifdef WNOHANG
6668 #ifndef WUNTRACED
6669 #define WUNTRACED 0
6670 #endif /* no WUNTRACED */
6671 /* Keep trying to get a status until we get a definitive result. */
6672 do
6673 {
6674 errno = 0;
6675 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6676 }
6677 while (pid < 0 && errno == EINTR);
6678
6679 if (pid <= 0)
6680 {
6681 /* PID == 0 means no processes found, PID == -1 means a real
6682 failure. We have done all our job, so return. */
6683
6684 /* USG systems forget handlers when they are used;
6685 must reestablish each time */
6686 #if defined (USG) && !defined (POSIX_SIGNALS)
6687 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6688 #endif
6689 errno = old_errno;
6690 return;
6691 }
6692 #else
6693 pid = wait (&w);
6694 #endif /* no WNOHANG */
6695
6696 /* Find the process that signaled us, and record its status. */
6697
6698 /* The process can have been deleted by Fdelete_process. */
6699 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6700 {
6701 Lisp_Object xpid = XCAR (tail);
6702 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6703 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6704 {
6705 XSETCAR (tail, Qnil);
6706 goto sigchld_end_of_loop;
6707 }
6708 }
6709
6710 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6711 p = 0;
6712 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6713 {
6714 proc = XCDR (XCAR (tail));
6715 p = XPROCESS (proc);
6716 if (EQ (p->type, Qreal) && p->pid == pid)
6717 break;
6718 p = 0;
6719 }
6720
6721 /* Look for an asynchronous process whose pid hasn't been filled
6722 in yet. */
6723 if (p == 0)
6724 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6725 {
6726 proc = XCDR (XCAR (tail));
6727 p = XPROCESS (proc);
6728 if (p->pid == -1)
6729 break;
6730 p = 0;
6731 }
6732
6733 /* Change the status of the process that was found. */
6734 if (p != 0)
6735 {
6736 int clear_desc_flag = 0;
6737
6738 p->tick = ++process_tick;
6739 p->raw_status = w;
6740 p->raw_status_new = 1;
6741
6742 /* If process has terminated, stop waiting for its output. */
6743 if ((WIFSIGNALED (w) || WIFEXITED (w))
6744 && p->infd >= 0)
6745 clear_desc_flag = 1;
6746
6747 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6748 if (clear_desc_flag)
6749 {
6750 FD_CLR (p->infd, &input_wait_mask);
6751 FD_CLR (p->infd, &non_keyboard_wait_mask);
6752 }
6753
6754 /* Tell wait_reading_process_output that it needs to wake up and
6755 look around. */
6756 if (input_available_clear_time)
6757 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6758 }
6759
6760 /* There was no asynchronous process found for that pid: we have
6761 a synchronous process. */
6762 else
6763 {
6764 synch_process_alive = 0;
6765
6766 /* Report the status of the synchronous process. */
6767 if (WIFEXITED (w))
6768 synch_process_retcode = WRETCODE (w);
6769 else if (WIFSIGNALED (w))
6770 synch_process_termsig = WTERMSIG (w);
6771
6772 /* Tell wait_reading_process_output that it needs to wake up and
6773 look around. */
6774 if (input_available_clear_time)
6775 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6776 }
6777
6778 sigchld_end_of_loop:
6779 ;
6780
6781 /* On some systems, we must return right away.
6782 If any more processes want to signal us, we will
6783 get another signal.
6784 Otherwise (on systems that have WNOHANG), loop around
6785 to use up all the processes that have something to tell us. */
6786 #if (defined WINDOWSNT \
6787 || (defined USG && !defined GNU_LINUX \
6788 && !(defined HPUX && defined WNOHANG)))
6789 #if defined (USG) && ! defined (POSIX_SIGNALS)
6790 signal (signo, sigchld_handler);
6791 #endif
6792 errno = old_errno;
6793 return;
6794 #endif /* USG, but not HPUX with WNOHANG */
6795 }
6796 }
6797 #endif /* SIGCHLD */
6798 \f
6799
6800 static Lisp_Object
6801 exec_sentinel_unwind (data)
6802 Lisp_Object data;
6803 {
6804 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6805 return Qnil;
6806 }
6807
6808 static Lisp_Object
6809 exec_sentinel_error_handler (error)
6810 Lisp_Object error;
6811 {
6812 cmd_error_internal (error, "error in process sentinel: ");
6813 Vinhibit_quit = Qt;
6814 update_echo_area ();
6815 Fsleep_for (make_number (2), Qnil);
6816 return Qt;
6817 }
6818
6819 static void
6820 exec_sentinel (proc, reason)
6821 Lisp_Object proc, reason;
6822 {
6823 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6824 register struct Lisp_Process *p = XPROCESS (proc);
6825 int count = SPECPDL_INDEX ();
6826 int outer_running_asynch_code = running_asynch_code;
6827 int waiting = waiting_for_user_input_p;
6828
6829 if (inhibit_sentinels)
6830 return;
6831
6832 /* No need to gcpro these, because all we do with them later
6833 is test them for EQness, and none of them should be a string. */
6834 odeactivate = Vdeactivate_mark;
6835 XSETBUFFER (obuffer, current_buffer);
6836 okeymap = current_buffer->keymap;
6837
6838 sentinel = p->sentinel;
6839 if (NILP (sentinel))
6840 return;
6841
6842 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6843 assure that it gets restored no matter how the sentinel exits. */
6844 p->sentinel = Qnil;
6845 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6846 /* Inhibit quit so that random quits don't screw up a running filter. */
6847 specbind (Qinhibit_quit, Qt);
6848 specbind (Qlast_nonmenu_event, Qt);
6849
6850 /* In case we get recursively called,
6851 and we already saved the match data nonrecursively,
6852 save the same match data in safely recursive fashion. */
6853 if (outer_running_asynch_code)
6854 {
6855 Lisp_Object tem;
6856 tem = Fmatch_data (Qnil, Qnil, Qnil);
6857 restore_search_regs ();
6858 record_unwind_save_match_data ();
6859 Fset_match_data (tem, Qt);
6860 }
6861
6862 /* For speed, if a search happens within this code,
6863 save the match data in a special nonrecursive fashion. */
6864 running_asynch_code = 1;
6865
6866 internal_condition_case_1 (read_process_output_call,
6867 Fcons (sentinel,
6868 Fcons (proc, Fcons (reason, Qnil))),
6869 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6870 exec_sentinel_error_handler);
6871
6872 /* If we saved the match data nonrecursively, restore it now. */
6873 restore_search_regs ();
6874 running_asynch_code = outer_running_asynch_code;
6875
6876 Vdeactivate_mark = odeactivate;
6877
6878 /* Restore waiting_for_user_input_p as it was
6879 when we were called, in case the filter clobbered it. */
6880 waiting_for_user_input_p = waiting;
6881
6882 #if 0
6883 if (! EQ (Fcurrent_buffer (), obuffer)
6884 || ! EQ (current_buffer->keymap, okeymap))
6885 #endif
6886 /* But do it only if the caller is actually going to read events.
6887 Otherwise there's no need to make him wake up, and it could
6888 cause trouble (for example it would make sit_for return). */
6889 if (waiting_for_user_input_p == -1)
6890 record_asynch_buffer_change ();
6891
6892 unbind_to (count, Qnil);
6893 }
6894
6895 /* Report all recent events of a change in process status
6896 (either run the sentinel or output a message).
6897 This is usually done while Emacs is waiting for keyboard input
6898 but can be done at other times. */
6899
6900 static void
6901 status_notify (deleting_process)
6902 struct Lisp_Process *deleting_process;
6903 {
6904 register Lisp_Object proc, buffer;
6905 Lisp_Object tail, msg;
6906 struct gcpro gcpro1, gcpro2;
6907
6908 tail = Qnil;
6909 msg = Qnil;
6910 /* We need to gcpro tail; if read_process_output calls a filter
6911 which deletes a process and removes the cons to which tail points
6912 from Vprocess_alist, and then causes a GC, tail is an unprotected
6913 reference. */
6914 GCPRO2 (tail, msg);
6915
6916 /* Set this now, so that if new processes are created by sentinels
6917 that we run, we get called again to handle their status changes. */
6918 update_tick = process_tick;
6919
6920 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6921 {
6922 Lisp_Object symbol;
6923 register struct Lisp_Process *p;
6924
6925 proc = Fcdr (XCAR (tail));
6926 p = XPROCESS (proc);
6927
6928 if (p->tick != p->update_tick)
6929 {
6930 p->update_tick = p->tick;
6931
6932 /* If process is still active, read any output that remains. */
6933 while (! EQ (p->filter, Qt)
6934 && ! EQ (p->status, Qconnect)
6935 && ! EQ (p->status, Qlisten)
6936 /* Network or serial process not stopped: */
6937 && ! EQ (p->command, Qt)
6938 && p->infd >= 0
6939 && p != deleting_process
6940 && read_process_output (proc, p->infd) > 0);
6941
6942 buffer = p->buffer;
6943
6944 /* Get the text to use for the message. */
6945 if (p->raw_status_new)
6946 update_status (p);
6947 msg = status_message (p);
6948
6949 /* If process is terminated, deactivate it or delete it. */
6950 symbol = p->status;
6951 if (CONSP (p->status))
6952 symbol = XCAR (p->status);
6953
6954 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6955 || EQ (symbol, Qclosed))
6956 {
6957 if (delete_exited_processes)
6958 remove_process (proc);
6959 else
6960 deactivate_process (proc);
6961 }
6962
6963 /* The actions above may have further incremented p->tick.
6964 So set p->update_tick again
6965 so that an error in the sentinel will not cause
6966 this code to be run again. */
6967 p->update_tick = p->tick;
6968 /* Now output the message suitably. */
6969 if (!NILP (p->sentinel))
6970 exec_sentinel (proc, msg);
6971 /* Don't bother with a message in the buffer
6972 when a process becomes runnable. */
6973 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6974 {
6975 Lisp_Object ro, tem;
6976 struct buffer *old = current_buffer;
6977 int opoint, opoint_byte;
6978 int before, before_byte;
6979
6980 ro = XBUFFER (buffer)->read_only;
6981
6982 /* Avoid error if buffer is deleted
6983 (probably that's why the process is dead, too) */
6984 if (NILP (XBUFFER (buffer)->name))
6985 continue;
6986 Fset_buffer (buffer);
6987
6988 opoint = PT;
6989 opoint_byte = PT_BYTE;
6990 /* Insert new output into buffer
6991 at the current end-of-output marker,
6992 thus preserving logical ordering of input and output. */
6993 if (XMARKER (p->mark)->buffer)
6994 Fgoto_char (p->mark);
6995 else
6996 SET_PT_BOTH (ZV, ZV_BYTE);
6997
6998 before = PT;
6999 before_byte = PT_BYTE;
7000
7001 tem = current_buffer->read_only;
7002 current_buffer->read_only = Qnil;
7003 insert_string ("\nProcess ");
7004 Finsert (1, &p->name);
7005 insert_string (" ");
7006 Finsert (1, &msg);
7007 current_buffer->read_only = tem;
7008 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7009
7010 if (opoint >= before)
7011 SET_PT_BOTH (opoint + (PT - before),
7012 opoint_byte + (PT_BYTE - before_byte));
7013 else
7014 SET_PT_BOTH (opoint, opoint_byte);
7015
7016 set_buffer_internal (old);
7017 }
7018 }
7019 } /* end for */
7020
7021 update_mode_lines++; /* in case buffers use %s in mode-line-format */
7022 redisplay_preserve_echo_area (13);
7023
7024 UNGCPRO;
7025 }
7026
7027 \f
7028 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7029 Sset_process_coding_system, 1, 3, 0,
7030 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7031 DECODING will be used to decode subprocess output and ENCODING to
7032 encode subprocess input. */)
7033 (process, decoding, encoding)
7034 register Lisp_Object process, decoding, encoding;
7035 {
7036 register struct Lisp_Process *p;
7037
7038 CHECK_PROCESS (process);
7039 p = XPROCESS (process);
7040 if (p->infd < 0)
7041 error ("Input file descriptor of %s closed", SDATA (p->name));
7042 if (p->outfd < 0)
7043 error ("Output file descriptor of %s closed", SDATA (p->name));
7044 Fcheck_coding_system (decoding);
7045 Fcheck_coding_system (encoding);
7046 encoding = coding_inherit_eol_type (encoding, Qnil);
7047 p->decode_coding_system = decoding;
7048 p->encode_coding_system = encoding;
7049 setup_process_coding_systems (process);
7050
7051 return Qnil;
7052 }
7053
7054 DEFUN ("process-coding-system",
7055 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7056 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7057 (process)
7058 register Lisp_Object process;
7059 {
7060 CHECK_PROCESS (process);
7061 return Fcons (XPROCESS (process)->decode_coding_system,
7062 XPROCESS (process)->encode_coding_system);
7063 }
7064
7065 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7066 Sset_process_filter_multibyte, 2, 2, 0,
7067 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7068 If FLAG is non-nil, the filter is given multibyte strings.
7069 If FLAG is nil, the filter is given unibyte strings. In this case,
7070 all character code conversion except for end-of-line conversion is
7071 suppressed. */)
7072 (process, flag)
7073 Lisp_Object process, flag;
7074 {
7075 register struct Lisp_Process *p;
7076
7077 CHECK_PROCESS (process);
7078 p = XPROCESS (process);
7079 if (NILP (flag))
7080 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
7081 setup_process_coding_systems (process);
7082
7083 return Qnil;
7084 }
7085
7086 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7087 Sprocess_filter_multibyte_p, 1, 1, 0,
7088 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7089 (process)
7090 Lisp_Object process;
7091 {
7092 register struct Lisp_Process *p;
7093 struct coding_system *coding;
7094
7095 CHECK_PROCESS (process);
7096 p = XPROCESS (process);
7097 coding = proc_decode_coding_system[p->infd];
7098 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7099 }
7100
7101
7102 \f
7103 /* Add DESC to the set of keyboard input descriptors. */
7104
7105 void
7106 add_keyboard_wait_descriptor (desc)
7107 int desc;
7108 {
7109 FD_SET (desc, &input_wait_mask);
7110 FD_SET (desc, &non_process_wait_mask);
7111 if (desc > max_keyboard_desc)
7112 max_keyboard_desc = desc;
7113 }
7114
7115 static int add_gpm_wait_descriptor_called_flag;
7116
7117 void
7118 add_gpm_wait_descriptor (desc)
7119 int desc;
7120 {
7121 if (! add_gpm_wait_descriptor_called_flag)
7122 FD_CLR (0, &input_wait_mask);
7123 add_gpm_wait_descriptor_called_flag = 1;
7124 FD_SET (desc, &input_wait_mask);
7125 FD_SET (desc, &gpm_wait_mask);
7126 if (desc > max_gpm_desc)
7127 max_gpm_desc = desc;
7128 }
7129
7130 /* From now on, do not expect DESC to give keyboard input. */
7131
7132 void
7133 delete_keyboard_wait_descriptor (desc)
7134 int desc;
7135 {
7136 int fd;
7137 int lim = max_keyboard_desc;
7138
7139 FD_CLR (desc, &input_wait_mask);
7140 FD_CLR (desc, &non_process_wait_mask);
7141
7142 if (desc == max_keyboard_desc)
7143 for (fd = 0; fd < lim; fd++)
7144 if (FD_ISSET (fd, &input_wait_mask)
7145 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7146 && !FD_ISSET (fd, &gpm_wait_mask))
7147 max_keyboard_desc = fd;
7148 }
7149
7150 void
7151 delete_gpm_wait_descriptor (desc)
7152 int desc;
7153 {
7154 int fd;
7155 int lim = max_gpm_desc;
7156
7157 FD_CLR (desc, &input_wait_mask);
7158 FD_CLR (desc, &non_process_wait_mask);
7159
7160 if (desc == max_gpm_desc)
7161 for (fd = 0; fd < lim; fd++)
7162 if (FD_ISSET (fd, &input_wait_mask)
7163 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7164 && !FD_ISSET (fd, &non_process_wait_mask))
7165 max_gpm_desc = fd;
7166 }
7167
7168 /* Return nonzero if *MASK has a bit set
7169 that corresponds to one of the keyboard input descriptors. */
7170
7171 static int
7172 keyboard_bit_set (mask)
7173 SELECT_TYPE *mask;
7174 {
7175 int fd;
7176
7177 for (fd = 0; fd <= max_keyboard_desc; fd++)
7178 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7179 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7180 return 1;
7181
7182 return 0;
7183 }
7184 \f
7185 void
7186 init_process ()
7187 {
7188 register int i;
7189
7190 inhibit_sentinels = 0;
7191
7192 #ifdef SIGCHLD
7193 #ifndef CANNOT_DUMP
7194 if (! noninteractive || initialized)
7195 #endif
7196 signal (SIGCHLD, sigchld_handler);
7197 #endif
7198
7199 FD_ZERO (&input_wait_mask);
7200 FD_ZERO (&non_keyboard_wait_mask);
7201 FD_ZERO (&non_process_wait_mask);
7202 max_process_desc = 0;
7203
7204 #ifdef NON_BLOCKING_CONNECT
7205 FD_ZERO (&connect_wait_mask);
7206 num_pending_connects = 0;
7207 #endif
7208
7209 #ifdef ADAPTIVE_READ_BUFFERING
7210 process_output_delay_count = 0;
7211 process_output_skip = 0;
7212 #endif
7213
7214 /* Don't do this, it caused infinite select loops. The display
7215 method should call add_keyboard_wait_descriptor on stdin if it
7216 needs that. */
7217 #if 0
7218 FD_SET (0, &input_wait_mask);
7219 #endif
7220
7221 Vprocess_alist = Qnil;
7222 #ifdef SIGCHLD
7223 deleted_pid_list = Qnil;
7224 #endif
7225 for (i = 0; i < MAXDESC; i++)
7226 {
7227 chan_process[i] = Qnil;
7228 proc_buffered_char[i] = -1;
7229 }
7230 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7231 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7232 #ifdef DATAGRAM_SOCKETS
7233 bzero (datagram_address, sizeof datagram_address);
7234 #endif
7235
7236 #ifdef HAVE_SOCKETS
7237 {
7238 Lisp_Object subfeatures = Qnil;
7239 struct socket_options *sopt;
7240
7241 #define ADD_SUBFEATURE(key, val) \
7242 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
7243
7244 #ifdef NON_BLOCKING_CONNECT
7245 ADD_SUBFEATURE (QCnowait, Qt);
7246 #endif
7247 #ifdef DATAGRAM_SOCKETS
7248 ADD_SUBFEATURE (QCtype, Qdatagram);
7249 #endif
7250 #ifdef HAVE_LOCAL_SOCKETS
7251 ADD_SUBFEATURE (QCfamily, Qlocal);
7252 #endif
7253 ADD_SUBFEATURE (QCfamily, Qipv4);
7254 #ifdef AF_INET6
7255 ADD_SUBFEATURE (QCfamily, Qipv6);
7256 #endif
7257 #ifdef HAVE_GETSOCKNAME
7258 ADD_SUBFEATURE (QCservice, Qt);
7259 #endif
7260 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7261 ADD_SUBFEATURE (QCserver, Qt);
7262 #endif
7263
7264 for (sopt = socket_options; sopt->name; sopt++)
7265 subfeatures = Fcons (intern (sopt->name), subfeatures);
7266
7267 Fprovide (intern ("make-network-process"), subfeatures);
7268 }
7269 #endif /* HAVE_SOCKETS */
7270
7271 #if defined (DARWIN) || defined (MAC_OSX)
7272 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7273 processes. As such, we only change the default value. */
7274 if (initialized)
7275 {
7276 char *release = get_operating_system_release();
7277 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7278 && release[1] == '.')) {
7279 Vprocess_connection_type = Qnil;
7280 }
7281 }
7282 #endif
7283 }
7284
7285 void
7286 syms_of_process ()
7287 {
7288 Qprocessp = intern ("processp");
7289 staticpro (&Qprocessp);
7290 Qrun = intern ("run");
7291 staticpro (&Qrun);
7292 Qstop = intern ("stop");
7293 staticpro (&Qstop);
7294 Qsignal = intern ("signal");
7295 staticpro (&Qsignal);
7296
7297 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7298 here again.
7299
7300 Qexit = intern ("exit");
7301 staticpro (&Qexit); */
7302
7303 Qopen = intern ("open");
7304 staticpro (&Qopen);
7305 Qclosed = intern ("closed");
7306 staticpro (&Qclosed);
7307 Qconnect = intern ("connect");
7308 staticpro (&Qconnect);
7309 Qfailed = intern ("failed");
7310 staticpro (&Qfailed);
7311 Qlisten = intern ("listen");
7312 staticpro (&Qlisten);
7313 Qlocal = intern ("local");
7314 staticpro (&Qlocal);
7315 Qipv4 = intern ("ipv4");
7316 staticpro (&Qipv4);
7317 #ifdef AF_INET6
7318 Qipv6 = intern ("ipv6");
7319 staticpro (&Qipv6);
7320 #endif
7321 Qdatagram = intern ("datagram");
7322 staticpro (&Qdatagram);
7323
7324 QCport = intern (":port");
7325 staticpro (&QCport);
7326 QCspeed = intern (":speed");
7327 staticpro (&QCspeed);
7328 QCprocess = intern (":process");
7329 staticpro (&QCprocess);
7330
7331 QCbytesize = intern (":bytesize");
7332 staticpro (&QCbytesize);
7333 QCstopbits = intern (":stopbits");
7334 staticpro (&QCstopbits);
7335 QCparity = intern (":parity");
7336 staticpro (&QCparity);
7337 Qodd = intern ("odd");
7338 staticpro (&Qodd);
7339 Qeven = intern ("even");
7340 staticpro (&Qeven);
7341 QCflowcontrol = intern (":flowcontrol");
7342 staticpro (&QCflowcontrol);
7343 Qhw = intern ("hw");
7344 staticpro (&Qhw);
7345 Qsw = intern ("sw");
7346 staticpro (&Qsw);
7347 QCsummary = intern (":summary");
7348 staticpro (&QCsummary);
7349
7350 Qreal = intern ("real");
7351 staticpro (&Qreal);
7352 Qnetwork = intern ("network");
7353 staticpro (&Qnetwork);
7354 Qserial = intern ("serial");
7355 staticpro (&Qserial);
7356
7357 QCname = intern (":name");
7358 staticpro (&QCname);
7359 QCbuffer = intern (":buffer");
7360 staticpro (&QCbuffer);
7361 QChost = intern (":host");
7362 staticpro (&QChost);
7363 QCservice = intern (":service");
7364 staticpro (&QCservice);
7365 QCtype = intern (":type");
7366 staticpro (&QCtype);
7367 QClocal = intern (":local");
7368 staticpro (&QClocal);
7369 QCremote = intern (":remote");
7370 staticpro (&QCremote);
7371 QCcoding = intern (":coding");
7372 staticpro (&QCcoding);
7373 QCserver = intern (":server");
7374 staticpro (&QCserver);
7375 QCnowait = intern (":nowait");
7376 staticpro (&QCnowait);
7377 QCsentinel = intern (":sentinel");
7378 staticpro (&QCsentinel);
7379 QClog = intern (":log");
7380 staticpro (&QClog);
7381 QCnoquery = intern (":noquery");
7382 staticpro (&QCnoquery);
7383 QCstop = intern (":stop");
7384 staticpro (&QCstop);
7385 QCoptions = intern (":options");
7386 staticpro (&QCoptions);
7387 QCplist = intern (":plist");
7388 staticpro (&QCplist);
7389
7390 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7391 staticpro (&Qlast_nonmenu_event);
7392
7393 staticpro (&Vprocess_alist);
7394 #ifdef SIGCHLD
7395 staticpro (&deleted_pid_list);
7396 #endif
7397
7398 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7399 doc: /* *Non-nil means delete processes immediately when they exit.
7400 A value of nil means don't delete them until `list-processes' is run. */);
7401
7402 delete_exited_processes = 1;
7403
7404 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7405 doc: /* Control type of device used to communicate with subprocesses.
7406 Values are nil to use a pipe, or t or `pty' to use a pty.
7407 The value has no effect if the system has no ptys or if all ptys are busy:
7408 then a pipe is used in any case.
7409 The value takes effect when `start-process' is called. */);
7410 Vprocess_connection_type = Qt;
7411
7412 #ifdef ADAPTIVE_READ_BUFFERING
7413 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7414 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7415 On some systems, when Emacs reads the output from a subprocess, the output data
7416 is read in very small blocks, potentially resulting in very poor performance.
7417 This behavior can be remedied to some extent by setting this variable to a
7418 non-nil value, as it will automatically delay reading from such processes, to
7419 allow them to produce more output before Emacs tries to read it.
7420 If the value is t, the delay is reset after each write to the process; any other
7421 non-nil value means that the delay is not reset on write.
7422 The variable takes effect when `start-process' is called. */);
7423 Vprocess_adaptive_read_buffering = Qt;
7424 #endif
7425
7426 defsubr (&Sprocessp);
7427 defsubr (&Sget_process);
7428 defsubr (&Sget_buffer_process);
7429 defsubr (&Sdelete_process);
7430 defsubr (&Sprocess_status);
7431 defsubr (&Sprocess_exit_status);
7432 defsubr (&Sprocess_id);
7433 defsubr (&Sprocess_name);
7434 defsubr (&Sprocess_tty_name);
7435 defsubr (&Sprocess_command);
7436 defsubr (&Sset_process_buffer);
7437 defsubr (&Sprocess_buffer);
7438 defsubr (&Sprocess_mark);
7439 defsubr (&Sset_process_filter);
7440 defsubr (&Sprocess_filter);
7441 defsubr (&Sset_process_sentinel);
7442 defsubr (&Sprocess_sentinel);
7443 defsubr (&Sset_process_window_size);
7444 defsubr (&Sset_process_inherit_coding_system_flag);
7445 defsubr (&Sprocess_inherit_coding_system_flag);
7446 defsubr (&Sset_process_query_on_exit_flag);
7447 defsubr (&Sprocess_query_on_exit_flag);
7448 defsubr (&Sprocess_contact);
7449 defsubr (&Sprocess_plist);
7450 defsubr (&Sset_process_plist);
7451 defsubr (&Slist_processes);
7452 defsubr (&Sprocess_list);
7453 defsubr (&Sstart_process);
7454 #ifdef HAVE_SERIAL
7455 defsubr (&Sserial_process_configure);
7456 defsubr (&Smake_serial_process);
7457 #endif /* HAVE_SERIAL */
7458 #ifdef HAVE_SOCKETS
7459 defsubr (&Sset_network_process_option);
7460 defsubr (&Smake_network_process);
7461 defsubr (&Sformat_network_address);
7462 #endif /* HAVE_SOCKETS */
7463 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7464 #ifdef SIOCGIFCONF
7465 defsubr (&Snetwork_interface_list);
7466 #endif
7467 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7468 defsubr (&Snetwork_interface_info);
7469 #endif
7470 #endif /* HAVE_SOCKETS ... */
7471 #ifdef DATAGRAM_SOCKETS
7472 defsubr (&Sprocess_datagram_address);
7473 defsubr (&Sset_process_datagram_address);
7474 #endif
7475 defsubr (&Saccept_process_output);
7476 defsubr (&Sprocess_send_region);
7477 defsubr (&Sprocess_send_string);
7478 defsubr (&Sinterrupt_process);
7479 defsubr (&Skill_process);
7480 defsubr (&Squit_process);
7481 defsubr (&Sstop_process);
7482 defsubr (&Scontinue_process);
7483 defsubr (&Sprocess_running_child_p);
7484 defsubr (&Sprocess_send_eof);
7485 defsubr (&Ssignal_process);
7486 defsubr (&Swaiting_for_user_input_p);
7487 defsubr (&Sprocess_type);
7488 defsubr (&Sset_process_coding_system);
7489 defsubr (&Sprocess_coding_system);
7490 defsubr (&Sset_process_filter_multibyte);
7491 defsubr (&Sprocess_filter_multibyte_p);
7492 }
7493
7494 \f
7495 #else /* not subprocesses */
7496
7497 #include <sys/types.h>
7498 #include <errno.h>
7499
7500 #include "lisp.h"
7501 #include "systime.h"
7502 #include "character.h"
7503 #include "coding.h"
7504 #include "termopts.h"
7505 #include "sysselect.h"
7506
7507 extern int frame_garbaged;
7508
7509 extern EMACS_TIME timer_check ();
7510 extern int timers_run;
7511
7512 Lisp_Object QCtype;
7513
7514 /* As described above, except assuming that there are no subprocesses:
7515
7516 Wait for timeout to elapse and/or keyboard input to be available.
7517
7518 time_limit is:
7519 timeout in seconds, or
7520 zero for no limit, or
7521 -1 means gobble data immediately available but don't wait for any.
7522
7523 read_kbd is a Lisp_Object:
7524 0 to ignore keyboard input, or
7525 1 to return when input is available, or
7526 -1 means caller will actually read the input, so don't throw to
7527 the quit handler.
7528
7529 see full version for other parameters. We know that wait_proc will
7530 always be NULL, since `subprocesses' isn't defined.
7531
7532 do_display != 0 means redisplay should be done to show subprocess
7533 output that arrives.
7534
7535 Return true if we received input from any process. */
7536
7537 int
7538 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7539 wait_for_cell, wait_proc, just_wait_proc)
7540 int time_limit, microsecs, read_kbd, do_display;
7541 Lisp_Object wait_for_cell;
7542 struct Lisp_Process *wait_proc;
7543 int just_wait_proc;
7544 {
7545 register int nfds;
7546 EMACS_TIME end_time, timeout;
7547 SELECT_TYPE waitchannels;
7548 int xerrno;
7549
7550 /* What does time_limit really mean? */
7551 if (time_limit || microsecs)
7552 {
7553 EMACS_GET_TIME (end_time);
7554 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7555 EMACS_ADD_TIME (end_time, end_time, timeout);
7556 }
7557
7558 /* Turn off periodic alarms (in case they are in use)
7559 and then turn off any other atimers,
7560 because the select emulator uses alarms. */
7561 stop_polling ();
7562 turn_on_atimers (0);
7563
7564 while (1)
7565 {
7566 int timeout_reduced_for_timers = 0;
7567
7568 /* If calling from keyboard input, do not quit
7569 since we want to return C-g as an input character.
7570 Otherwise, do pending quit if requested. */
7571 if (read_kbd >= 0)
7572 QUIT;
7573
7574 /* Exit now if the cell we're waiting for became non-nil. */
7575 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7576 break;
7577
7578 /* Compute time from now till when time limit is up */
7579 /* Exit if already run out */
7580 if (time_limit == -1)
7581 {
7582 /* -1 specified for timeout means
7583 gobble output available now
7584 but don't wait at all. */
7585
7586 EMACS_SET_SECS_USECS (timeout, 0, 0);
7587 }
7588 else if (time_limit || microsecs)
7589 {
7590 EMACS_GET_TIME (timeout);
7591 EMACS_SUB_TIME (timeout, end_time, timeout);
7592 if (EMACS_TIME_NEG_P (timeout))
7593 break;
7594 }
7595 else
7596 {
7597 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7598 }
7599
7600 /* If our caller will not immediately handle keyboard events,
7601 run timer events directly.
7602 (Callers that will immediately read keyboard events
7603 call timer_delay on their own.) */
7604 if (NILP (wait_for_cell))
7605 {
7606 EMACS_TIME timer_delay;
7607
7608 do
7609 {
7610 int old_timers_run = timers_run;
7611 timer_delay = timer_check (1);
7612 if (timers_run != old_timers_run && do_display)
7613 /* We must retry, since a timer may have requeued itself
7614 and that could alter the time delay. */
7615 redisplay_preserve_echo_area (14);
7616 else
7617 break;
7618 }
7619 while (!detect_input_pending ());
7620
7621 /* If there is unread keyboard input, also return. */
7622 if (read_kbd != 0
7623 && requeued_events_pending_p ())
7624 break;
7625
7626 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7627 {
7628 EMACS_TIME difference;
7629 EMACS_SUB_TIME (difference, timer_delay, timeout);
7630 if (EMACS_TIME_NEG_P (difference))
7631 {
7632 timeout = timer_delay;
7633 timeout_reduced_for_timers = 1;
7634 }
7635 }
7636 }
7637
7638 /* Cause C-g and alarm signals to take immediate action,
7639 and cause input available signals to zero out timeout. */
7640 if (read_kbd < 0)
7641 set_waiting_for_input (&timeout);
7642
7643 /* Wait till there is something to do. */
7644
7645 if (! read_kbd && NILP (wait_for_cell))
7646 FD_ZERO (&waitchannels);
7647 else
7648 FD_SET (0, &waitchannels);
7649
7650 /* If a frame has been newly mapped and needs updating,
7651 reprocess its display stuff. */
7652 if (frame_garbaged && do_display)
7653 {
7654 clear_waiting_for_input ();
7655 redisplay_preserve_echo_area (15);
7656 if (read_kbd < 0)
7657 set_waiting_for_input (&timeout);
7658 }
7659
7660 if (read_kbd && detect_input_pending ())
7661 {
7662 nfds = 0;
7663 FD_ZERO (&waitchannels);
7664 }
7665 else
7666 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7667 &timeout);
7668
7669 xerrno = errno;
7670
7671 /* Make C-g and alarm signals set flags again */
7672 clear_waiting_for_input ();
7673
7674 /* If we woke up due to SIGWINCH, actually change size now. */
7675 do_pending_window_change (0);
7676
7677 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7678 /* We waited the full specified time, so return now. */
7679 break;
7680
7681 if (nfds == -1)
7682 {
7683 /* If the system call was interrupted, then go around the
7684 loop again. */
7685 if (xerrno == EINTR)
7686 FD_ZERO (&waitchannels);
7687 else
7688 error ("select error: %s", emacs_strerror (xerrno));
7689 }
7690 #ifdef SOLARIS2
7691 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7692 /* System sometimes fails to deliver SIGIO. */
7693 kill (getpid (), SIGIO);
7694 #endif
7695 #ifdef SIGIO
7696 if (read_kbd && interrupt_input && (waitchannels & 1))
7697 kill (getpid (), SIGIO);
7698 #endif
7699
7700 /* Check for keyboard input */
7701
7702 if (read_kbd
7703 && detect_input_pending_run_timers (do_display))
7704 {
7705 swallow_events (do_display);
7706 if (detect_input_pending_run_timers (do_display))
7707 break;
7708 }
7709
7710 /* If there is unread keyboard input, also return. */
7711 if (read_kbd
7712 && requeued_events_pending_p ())
7713 break;
7714
7715 /* If wait_for_cell. check for keyboard input
7716 but don't run any timers.
7717 ??? (It seems wrong to me to check for keyboard
7718 input at all when wait_for_cell, but the code
7719 has been this way since July 1994.
7720 Try changing this after version 19.31.) */
7721 if (! NILP (wait_for_cell)
7722 && detect_input_pending ())
7723 {
7724 swallow_events (do_display);
7725 if (detect_input_pending ())
7726 break;
7727 }
7728
7729 /* Exit now if the cell we're waiting for became non-nil. */
7730 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7731 break;
7732 }
7733
7734 start_polling ();
7735
7736 return 0;
7737 }
7738
7739
7740 /* Don't confuse make-docfile by having two doc strings for this function.
7741 make-docfile does not pay attention to #if, for good reason! */
7742 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7743 0)
7744 (name)
7745 register Lisp_Object name;
7746 {
7747 return Qnil;
7748 }
7749
7750 /* Don't confuse make-docfile by having two doc strings for this function.
7751 make-docfile does not pay attention to #if, for good reason! */
7752 DEFUN ("process-inherit-coding-system-flag",
7753 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7754 1, 1, 0,
7755 0)
7756 (process)
7757 register Lisp_Object process;
7758 {
7759 /* Ignore the argument and return the value of
7760 inherit-process-coding-system. */
7761 return inherit_process_coding_system ? Qt : Qnil;
7762 }
7763
7764 /* Kill all processes associated with `buffer'.
7765 If `buffer' is nil, kill all processes.
7766 Since we have no subprocesses, this does nothing. */
7767
7768 void
7769 kill_buffer_processes (buffer)
7770 Lisp_Object buffer;
7771 {
7772 }
7773
7774 void
7775 init_process ()
7776 {
7777 }
7778
7779 void
7780 syms_of_process ()
7781 {
7782 QCtype = intern (":type");
7783 staticpro (&QCtype);
7784
7785 defsubr (&Sget_buffer_process);
7786 defsubr (&Sprocess_inherit_coding_system_flag);
7787 }
7788
7789 \f
7790 #endif /* not subprocesses */
7791
7792 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7793 (do not change this comment) */