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