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