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 Lisp_Object old_window = selected_window;
4366
4367 timer_delay = timer_check (1);
4368
4369 /* If a timer has run, this might have changed buffers
4370 an alike. Make read_key_sequence aware of that. */
4371 if (timers_run != old_timers_run
4372 && (old_buffer != current_buffer
4373 || !EQ (old_window, selected_window))
4374 && waiting_for_user_input_p == -1)
4375 record_asynch_buffer_change ();
4376
4377 if (timers_run != old_timers_run && do_display)
4378 /* We must retry, since a timer may have requeued itself
4379 and that could alter the time_delay. */
4380 redisplay_preserve_echo_area (9);
4381 else
4382 break;
4383 }
4384 while (!detect_input_pending ());
4385
4386 /* If there is unread keyboard input, also return. */
4387 if (read_kbd != 0
4388 && requeued_events_pending_p ())
4389 break;
4390
4391 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4392 {
4393 EMACS_TIME difference;
4394 EMACS_SUB_TIME (difference, timer_delay, timeout);
4395 if (EMACS_TIME_NEG_P (difference))
4396 {
4397 timeout = timer_delay;
4398 timeout_reduced_for_timers = 1;
4399 }
4400 }
4401 /* If time_limit is -1, we are not going to wait at all. */
4402 else if (time_limit != -1)
4403 {
4404 /* This is so a breakpoint can be put here. */
4405 wait_reading_process_output_1 ();
4406 }
4407 }
4408
4409 /* Cause C-g and alarm signals to take immediate action,
4410 and cause input available signals to zero out timeout.
4411
4412 It is important that we do this before checking for process
4413 activity. If we get a SIGCHLD after the explicit checks for
4414 process activity, timeout is the only way we will know. */
4415 if (read_kbd < 0)
4416 set_waiting_for_input (&timeout);
4417
4418 /* If status of something has changed, and no input is
4419 available, notify the user of the change right away. After
4420 this explicit check, we'll let the SIGCHLD handler zap
4421 timeout to get our attention. */
4422 if (update_tick != process_tick && do_display)
4423 {
4424 SELECT_TYPE Atemp;
4425 #ifdef NON_BLOCKING_CONNECT
4426 SELECT_TYPE Ctemp;
4427 #endif
4428
4429 Atemp = input_wait_mask;
4430 #if 0
4431 /* On Mac OS X 10.0, the SELECT system call always says input is
4432 present (for reading) at stdin, even when none is. This
4433 causes the call to SELECT below to return 1 and
4434 status_notify not to be called. As a result output of
4435 subprocesses are incorrectly discarded.
4436 */
4437 FD_CLR (0, &Atemp);
4438 #endif
4439 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4440
4441 EMACS_SET_SECS_USECS (timeout, 0, 0);
4442 if ((select (max (max (max_process_desc, max_keyboard_desc),
4443 max_gpm_desc) + 1,
4444 &Atemp,
4445 #ifdef NON_BLOCKING_CONNECT
4446 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4447 #else
4448 (SELECT_TYPE *)0,
4449 #endif
4450 (SELECT_TYPE *)0, &timeout)
4451 <= 0))
4452 {
4453 /* It's okay for us to do this and then continue with
4454 the loop, since timeout has already been zeroed out. */
4455 clear_waiting_for_input ();
4456 status_notify (NULL);
4457 }
4458 }
4459
4460 /* Don't wait for output from a non-running process. Just
4461 read whatever data has already been received. */
4462 if (wait_proc && wait_proc->raw_status_new)
4463 update_status (wait_proc);
4464 if (wait_proc
4465 && ! EQ (wait_proc->status, Qrun)
4466 && ! EQ (wait_proc->status, Qconnect))
4467 {
4468 int nread, total_nread = 0;
4469
4470 clear_waiting_for_input ();
4471 XSETPROCESS (proc, wait_proc);
4472
4473 /* Read data from the process, until we exhaust it. */
4474 while (wait_proc->infd >= 0)
4475 {
4476 nread = read_process_output (proc, wait_proc->infd);
4477
4478 if (nread == 0)
4479 break;
4480
4481 if (0 < nread)
4482 total_nread += nread;
4483 #ifdef EIO
4484 else if (nread == -1 && EIO == errno)
4485 break;
4486 #endif
4487 #ifdef EAGAIN
4488 else if (nread == -1 && EAGAIN == errno)
4489 break;
4490 #endif
4491 #ifdef EWOULDBLOCK
4492 else if (nread == -1 && EWOULDBLOCK == errno)
4493 break;
4494 #endif
4495 }
4496 if (total_nread > 0 && do_display)
4497 redisplay_preserve_echo_area (10);
4498
4499 break;
4500 }
4501
4502 /* Wait till there is something to do */
4503
4504 if (wait_proc && just_wait_proc)
4505 {
4506 if (wait_proc->infd < 0) /* Terminated */
4507 break;
4508 FD_SET (wait_proc->infd, &Available);
4509 check_delay = 0;
4510 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4511 }
4512 else if (!NILP (wait_for_cell))
4513 {
4514 Available = non_process_wait_mask;
4515 check_delay = 0;
4516 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4517 }
4518 else
4519 {
4520 if (! read_kbd)
4521 Available = non_keyboard_wait_mask;
4522 else
4523 Available = input_wait_mask;
4524 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4525 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4526 }
4527
4528 /* If frame size has changed or the window is newly mapped,
4529 redisplay now, before we start to wait. There is a race
4530 condition here; if a SIGIO arrives between now and the select
4531 and indicates that a frame is trashed, the select may block
4532 displaying a trashed screen. */
4533 if (frame_garbaged && do_display)
4534 {
4535 clear_waiting_for_input ();
4536 redisplay_preserve_echo_area (11);
4537 if (read_kbd < 0)
4538 set_waiting_for_input (&timeout);
4539 }
4540
4541 no_avail = 0;
4542 if (read_kbd && detect_input_pending ())
4543 {
4544 nfds = 0;
4545 no_avail = 1;
4546 }
4547 else
4548 {
4549 #ifdef NON_BLOCKING_CONNECT
4550 if (check_connect)
4551 Connecting = connect_wait_mask;
4552 #endif
4553
4554 #ifdef ADAPTIVE_READ_BUFFERING
4555 /* Set the timeout for adaptive read buffering if any
4556 process has non-zero read_output_skip and non-zero
4557 read_output_delay, and we are not reading output for a
4558 specific wait_channel. It is not executed if
4559 Vprocess_adaptive_read_buffering is nil. */
4560 if (process_output_skip && check_delay > 0)
4561 {
4562 int usecs = EMACS_USECS (timeout);
4563 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4564 usecs = READ_OUTPUT_DELAY_MAX;
4565 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4566 {
4567 proc = chan_process[channel];
4568 if (NILP (proc))
4569 continue;
4570 /* Find minimum non-zero read_output_delay among the
4571 processes with non-zero read_output_skip. */
4572 if (XPROCESS (proc)->read_output_delay > 0)
4573 {
4574 check_delay--;
4575 if (!XPROCESS (proc)->read_output_skip)
4576 continue;
4577 FD_CLR (channel, &Available);
4578 XPROCESS (proc)->read_output_skip = 0;
4579 if (XPROCESS (proc)->read_output_delay < usecs)
4580 usecs = XPROCESS (proc)->read_output_delay;
4581 }
4582 }
4583 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4584 process_output_skip = 0;
4585 }
4586 #endif
4587
4588 nfds = select (max (max (max_process_desc, max_keyboard_desc),
4589 max_gpm_desc) + 1,
4590 &Available,
4591 #ifdef NON_BLOCKING_CONNECT
4592 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4593 #else
4594 (SELECT_TYPE *)0,
4595 #endif
4596 (SELECT_TYPE *)0, &timeout);
4597 }
4598
4599 xerrno = errno;
4600
4601 /* Make C-g and alarm signals set flags again */
4602 clear_waiting_for_input ();
4603
4604 /* If we woke up due to SIGWINCH, actually change size now. */
4605 do_pending_window_change (0);
4606
4607 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4608 /* We wanted the full specified time, so return now. */
4609 break;
4610 if (nfds < 0)
4611 {
4612 if (xerrno == EINTR)
4613 no_avail = 1;
4614 #ifdef ultrix
4615 /* Ultrix select seems to return ENOMEM when it is
4616 interrupted. Treat it just like EINTR. Bleah. Note
4617 that we want to test for the "ultrix" CPP symbol, not
4618 "__ultrix__"; the latter is only defined under GCC, but
4619 not by DEC's bundled CC. -JimB */
4620 else if (xerrno == ENOMEM)
4621 no_avail = 1;
4622 #endif
4623 else if (xerrno == EBADF)
4624 {
4625 #ifdef AIX
4626 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4627 the child's closure of the pts gives the parent a SIGHUP, and
4628 the ptc file descriptor is automatically closed,
4629 yielding EBADF here or at select() call above.
4630 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4631 in m/ibmrt-aix.h), and here we just ignore the select error.
4632 Cleanup occurs c/o status_notify after SIGCLD. */
4633 no_avail = 1; /* Cannot depend on values returned */
4634 #else
4635 abort ();
4636 #endif
4637 }
4638 else
4639 error ("select error: %s", emacs_strerror (xerrno));
4640 }
4641
4642 if (no_avail)
4643 {
4644 FD_ZERO (&Available);
4645 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4646 }
4647
4648 #if defined(sun) && !defined(USG5_4)
4649 if (nfds > 0 && keyboard_bit_set (&Available)
4650 && interrupt_input)
4651 /* System sometimes fails to deliver SIGIO.
4652
4653 David J. Mackenzie says that Emacs doesn't compile under
4654 Solaris if this code is enabled, thus the USG5_4 in the CPP
4655 conditional. "I haven't noticed any ill effects so far.
4656 If you find a Solaris expert somewhere, they might know
4657 better." */
4658 kill (getpid (), SIGIO);
4659 #endif
4660
4661 #if 0 /* When polling is used, interrupt_input is 0,
4662 so get_input_pending should read the input.
4663 So this should not be needed. */
4664 /* If we are using polling for input,
4665 and we see input available, make it get read now.
4666 Otherwise it might not actually get read for a second.
4667 And on hpux, since we turn off polling in wait_reading_process_output,
4668 it might never get read at all if we don't spend much time
4669 outside of wait_reading_process_output. */
4670 if (read_kbd && interrupt_input
4671 && keyboard_bit_set (&Available)
4672 && input_polling_used ())
4673 kill (getpid (), SIGALRM);
4674 #endif
4675
4676 /* Check for keyboard input */
4677 /* If there is any, return immediately
4678 to give it higher priority than subprocesses */
4679
4680 if (read_kbd != 0)
4681 {
4682 int old_timers_run = timers_run;
4683 struct buffer *old_buffer = current_buffer;
4684 Lisp_Object old_window = selected_window;
4685 int leave = 0;
4686
4687 if (detect_input_pending_run_timers (do_display))
4688 {
4689 swallow_events (do_display);
4690 if (detect_input_pending_run_timers (do_display))
4691 leave = 1;
4692 }
4693
4694 /* If a timer has run, this might have changed buffers
4695 an alike. Make read_key_sequence aware of that. */
4696 if (timers_run != old_timers_run
4697 && waiting_for_user_input_p == -1
4698 && (old_buffer != current_buffer
4699 || !EQ (old_window, selected_window)))
4700 record_asynch_buffer_change ();
4701
4702 if (leave)
4703 break;
4704 }
4705
4706 /* If there is unread keyboard input, also return. */
4707 if (read_kbd != 0
4708 && requeued_events_pending_p ())
4709 break;
4710
4711 /* If we are not checking for keyboard input now,
4712 do process events (but don't run any timers).
4713 This is so that X events will be processed.
4714 Otherwise they may have to wait until polling takes place.
4715 That would causes delays in pasting selections, for example.
4716
4717 (We used to do this only if wait_for_cell.) */
4718 if (read_kbd == 0 && detect_input_pending ())
4719 {
4720 swallow_events (do_display);
4721 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4722 if (detect_input_pending ())
4723 break;
4724 #endif
4725 }
4726
4727 /* Exit now if the cell we're waiting for became non-nil. */
4728 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4729 break;
4730
4731 #ifdef SIGIO
4732 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4733 go read it. This can happen with X on BSD after logging out.
4734 In that case, there really is no input and no SIGIO,
4735 but select says there is input. */
4736
4737 if (read_kbd && interrupt_input
4738 && keyboard_bit_set (&Available) && ! noninteractive)
4739 kill (getpid (), SIGIO);
4740 #endif
4741
4742 if (! wait_proc)
4743 got_some_input |= nfds > 0;
4744
4745 /* If checking input just got us a size-change event from X,
4746 obey it now if we should. */
4747 if (read_kbd || ! NILP (wait_for_cell))
4748 do_pending_window_change (0);
4749
4750 /* Check for data from a process. */
4751 if (no_avail || nfds == 0)
4752 continue;
4753
4754 /* Really FIRST_PROC_DESC should be 0 on Unix,
4755 but this is safer in the short run. */
4756 for (channel = 0; channel <= max_process_desc; channel++)
4757 {
4758 if (FD_ISSET (channel, &Available)
4759 && FD_ISSET (channel, &non_keyboard_wait_mask))
4760 {
4761 int nread;
4762
4763 /* If waiting for this channel, arrange to return as
4764 soon as no more input to be processed. No more
4765 waiting. */
4766 if (wait_channel == channel)
4767 {
4768 wait_channel = -1;
4769 time_limit = -1;
4770 got_some_input = 1;
4771 }
4772 proc = chan_process[channel];
4773 if (NILP (proc))
4774 continue;
4775
4776 /* If this is a server stream socket, accept connection. */
4777 if (EQ (XPROCESS (proc)->status, Qlisten))
4778 {
4779 server_accept_connection (proc, channel);
4780 continue;
4781 }
4782
4783 /* Read data from the process, starting with our
4784 buffered-ahead character if we have one. */
4785
4786 nread = read_process_output (proc, channel);
4787 if (nread > 0)
4788 {
4789 /* Since read_process_output can run a filter,
4790 which can call accept-process-output,
4791 don't try to read from any other processes
4792 before doing the select again. */
4793 FD_ZERO (&Available);
4794
4795 if (do_display)
4796 redisplay_preserve_echo_area (12);
4797 }
4798 #ifdef EWOULDBLOCK
4799 else if (nread == -1 && errno == EWOULDBLOCK)
4800 ;
4801 #endif
4802 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
4803 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
4804 #ifdef O_NONBLOCK
4805 else if (nread == -1 && errno == EAGAIN)
4806 ;
4807 #else
4808 #ifdef O_NDELAY
4809 else if (nread == -1 && errno == EAGAIN)
4810 ;
4811 /* Note that we cannot distinguish between no input
4812 available now and a closed pipe.
4813 With luck, a closed pipe will be accompanied by
4814 subprocess termination and SIGCHLD. */
4815 else if (nread == 0 && !NETCONN_P (proc))
4816 ;
4817 #endif /* O_NDELAY */
4818 #endif /* O_NONBLOCK */
4819 #ifdef HAVE_PTYS
4820 /* On some OSs with ptys, when the process on one end of
4821 a pty exits, the other end gets an error reading with
4822 errno = EIO instead of getting an EOF (0 bytes read).
4823 Therefore, if we get an error reading and errno =
4824 EIO, just continue, because the child process has
4825 exited and should clean itself up soon (e.g. when we
4826 get a SIGCHLD).
4827
4828 However, it has been known to happen that the SIGCHLD
4829 got lost. So raise the signal again just in case.
4830 It can't hurt. */
4831 else if (nread == -1 && errno == EIO)
4832 {
4833 /* Clear the descriptor now, so we only raise the signal once. */
4834 FD_CLR (channel, &input_wait_mask);
4835 FD_CLR (channel, &non_keyboard_wait_mask);
4836
4837 kill (getpid (), SIGCHLD);
4838 }
4839 #endif /* HAVE_PTYS */
4840 /* If we can detect process termination, don't consider the process
4841 gone just because its pipe is closed. */
4842 #ifdef SIGCHLD
4843 else if (nread == 0 && !NETCONN_P (proc))
4844 ;
4845 #endif
4846 else
4847 {
4848 /* Preserve status of processes already terminated. */
4849 XPROCESS (proc)->tick = ++process_tick;
4850 deactivate_process (proc);
4851 if (XPROCESS (proc)->raw_status_new)
4852 update_status (XPROCESS (proc));
4853 if (EQ (XPROCESS (proc)->status, Qrun))
4854 XPROCESS (proc)->status
4855 = Fcons (Qexit, Fcons (make_number (256), Qnil));
4856 }
4857 }
4858 #ifdef NON_BLOCKING_CONNECT
4859 if (check_connect && FD_ISSET (channel, &Connecting)
4860 && FD_ISSET (channel, &connect_wait_mask))
4861 {
4862 struct Lisp_Process *p;
4863
4864 FD_CLR (channel, &connect_wait_mask);
4865 if (--num_pending_connects < 0)
4866 abort ();
4867
4868 proc = chan_process[channel];
4869 if (NILP (proc))
4870 continue;
4871
4872 p = XPROCESS (proc);
4873
4874 #ifdef GNU_LINUX
4875 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
4876 So only use it on systems where it is known to work. */
4877 {
4878 int xlen = sizeof(xerrno);
4879 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
4880 xerrno = errno;
4881 }
4882 #else
4883 {
4884 struct sockaddr pname;
4885 int pnamelen = sizeof(pname);
4886
4887 /* If connection failed, getpeername will fail. */
4888 xerrno = 0;
4889 if (getpeername(channel, &pname, &pnamelen) < 0)
4890 {
4891 /* Obtain connect failure code through error slippage. */
4892 char dummy;
4893 xerrno = errno;
4894 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
4895 xerrno = errno;
4896 }
4897 }
4898 #endif
4899 if (xerrno)
4900 {
4901 p->tick = ++process_tick;
4902 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
4903 deactivate_process (proc);
4904 }
4905 else
4906 {
4907 p->status = Qrun;
4908 /* Execute the sentinel here. If we had relied on
4909 status_notify to do it later, it will read input
4910 from the process before calling the sentinel. */
4911 exec_sentinel (proc, build_string ("open\n"));
4912 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
4913 {
4914 FD_SET (p->infd, &input_wait_mask);
4915 FD_SET (p->infd, &non_keyboard_wait_mask);
4916 }
4917 }
4918 }
4919 #endif /* NON_BLOCKING_CONNECT */
4920 } /* end for each file descriptor */
4921 } /* end while exit conditions not met */
4922
4923 unbind_to (count, Qnil);
4924
4925 /* If calling from keyboard input, do not quit
4926 since we want to return C-g as an input character.
4927 Otherwise, do pending quit if requested. */
4928 if (read_kbd >= 0)
4929 {
4930 /* Prevent input_pending from remaining set if we quit. */
4931 clear_input_pending ();
4932 QUIT;
4933 }
4934 #ifdef POLL_INTERRUPTED_SYS_CALL
4935 /* AlainF 5-Jul-1996
4936 HP-UX 10.10 seems to have problems with signals coming in
4937 Causes "poll: interrupted system call" messages when Emacs is run
4938 in an X window
4939 Turn periodic alarms back on */
4940 start_polling ();
4941 #endif /* POLL_INTERRUPTED_SYS_CALL */
4942
4943 return got_some_input;
4944 }
4945 \f
4946 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
4947
4948 static Lisp_Object
4949 read_process_output_call (fun_and_args)
4950 Lisp_Object fun_and_args;
4951 {
4952 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
4953 }
4954
4955 static Lisp_Object
4956 read_process_output_error_handler (error)
4957 Lisp_Object error;
4958 {
4959 cmd_error_internal (error, "error in process filter: ");
4960 Vinhibit_quit = Qt;
4961 update_echo_area ();
4962 Fsleep_for (make_number (2), Qnil);
4963 return Qt;
4964 }
4965
4966 /* Read pending output from the process channel,
4967 starting with our buffered-ahead character if we have one.
4968 Yield number of decoded characters read.
4969
4970 This function reads at most 4096 characters.
4971 If you want to read all available subprocess output,
4972 you must call it repeatedly until it returns zero.
4973
4974 The characters read are decoded according to PROC's coding-system
4975 for decoding. */
4976
4977 static int
4978 read_process_output (proc, channel)
4979 Lisp_Object proc;
4980 register int channel;
4981 {
4982 register int nbytes;
4983 char *chars;
4984 register Lisp_Object outstream;
4985 register struct buffer *old = current_buffer;
4986 register struct Lisp_Process *p = XPROCESS (proc);
4987 register int opoint;
4988 struct coding_system *coding = proc_decode_coding_system[channel];
4989 int carryover = p->decoding_carryover;
4990 int readmax = 4096;
4991
4992 #ifdef VMS
4993 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
4994
4995 vs = get_vms_process_pointer (p->pid);
4996 if (vs)
4997 {
4998 if (!vs->iosb[0])
4999 return (0); /* Really weird if it does this */
5000 if (!(vs->iosb[0] & 1))
5001 return -1; /* I/O error */
5002 }
5003 else
5004 error ("Could not get VMS process pointer");
5005 chars = vs->inputBuffer;
5006 nbytes = clean_vms_buffer (chars, vs->iosb[1]);
5007 if (nbytes <= 0)
5008 {
5009 start_vms_process_read (vs); /* Crank up the next read on the process */
5010 return 1; /* Nothing worth printing, say we got 1 */
5011 }
5012 if (carryover > 0)
5013 {
5014 /* The data carried over in the previous decoding (which are at
5015 the tail of decoding buffer) should be prepended to the new
5016 data read to decode all together. */
5017 chars = (char *) alloca (nbytes + carryover);
5018 bcopy (SDATA (p->decoding_buf), buf, carryover);
5019 bcopy (vs->inputBuffer, chars + carryover, nbytes);
5020 }
5021 #else /* not VMS */
5022
5023 chars = (char *) alloca (carryover + readmax);
5024 if (carryover)
5025 /* See the comment above. */
5026 bcopy (SDATA (p->decoding_buf), chars, carryover);
5027
5028 #ifdef DATAGRAM_SOCKETS
5029 /* We have a working select, so proc_buffered_char is always -1. */
5030 if (DATAGRAM_CHAN_P (channel))
5031 {
5032 int len = datagram_address[channel].len;
5033 nbytes = recvfrom (channel, chars + carryover, readmax,
5034 0, datagram_address[channel].sa, &len);
5035 }
5036 else
5037 #endif
5038 if (proc_buffered_char[channel] < 0)
5039 {
5040 nbytes = emacs_read (channel, chars + carryover, readmax);
5041 #ifdef ADAPTIVE_READ_BUFFERING
5042 if (nbytes > 0 && p->adaptive_read_buffering)
5043 {
5044 int delay = p->read_output_delay;
5045 if (nbytes < 256)
5046 {
5047 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5048 {
5049 if (delay == 0)
5050 process_output_delay_count++;
5051 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5052 }
5053 }
5054 else if (delay > 0 && (nbytes == readmax))
5055 {
5056 delay -= READ_OUTPUT_DELAY_INCREMENT;
5057 if (delay == 0)
5058 process_output_delay_count--;
5059 }
5060 p->read_output_delay = delay;
5061 if (delay)
5062 {
5063 p->read_output_skip = 1;
5064 process_output_skip = 1;
5065 }
5066 }
5067 #endif
5068 }
5069 else
5070 {
5071 chars[carryover] = proc_buffered_char[channel];
5072 proc_buffered_char[channel] = -1;
5073 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5074 if (nbytes < 0)
5075 nbytes = 1;
5076 else
5077 nbytes = nbytes + 1;
5078 }
5079 #endif /* not VMS */
5080
5081 p->decoding_carryover = 0;
5082
5083 /* At this point, NBYTES holds number of bytes just received
5084 (including the one in proc_buffered_char[channel]). */
5085 if (nbytes <= 0)
5086 {
5087 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5088 return nbytes;
5089 coding->mode |= CODING_MODE_LAST_BLOCK;
5090 }
5091
5092 /* Now set NBYTES how many bytes we must decode. */
5093 nbytes += carryover;
5094
5095 /* Read and dispose of the process output. */
5096 outstream = p->filter;
5097 if (!NILP (outstream))
5098 {
5099 /* We inhibit quit here instead of just catching it so that
5100 hitting ^G when a filter happens to be running won't screw
5101 it up. */
5102 int count = SPECPDL_INDEX ();
5103 Lisp_Object odeactivate;
5104 Lisp_Object obuffer, okeymap;
5105 Lisp_Object text;
5106 int outer_running_asynch_code = running_asynch_code;
5107 int waiting = waiting_for_user_input_p;
5108
5109 /* No need to gcpro these, because all we do with them later
5110 is test them for EQness, and none of them should be a string. */
5111 odeactivate = Vdeactivate_mark;
5112 XSETBUFFER (obuffer, current_buffer);
5113 okeymap = current_buffer->keymap;
5114
5115 specbind (Qinhibit_quit, Qt);
5116 specbind (Qlast_nonmenu_event, Qt);
5117
5118 /* In case we get recursively called,
5119 and we already saved the match data nonrecursively,
5120 save the same match data in safely recursive fashion. */
5121 if (outer_running_asynch_code)
5122 {
5123 Lisp_Object tem;
5124 /* Don't clobber the CURRENT match data, either! */
5125 tem = Fmatch_data (Qnil, Qnil, Qnil);
5126 restore_search_regs ();
5127 record_unwind_save_match_data ();
5128 Fset_match_data (tem, Qt);
5129 }
5130
5131 /* For speed, if a search happens within this code,
5132 save the match data in a special nonrecursive fashion. */
5133 running_asynch_code = 1;
5134
5135 decode_coding_c_string (coding, chars, nbytes, Qt);
5136 text = coding->dst_object;
5137 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5138 /* A new coding system might be found. */
5139 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5140 {
5141 p->decode_coding_system = Vlast_coding_system_used;
5142
5143 /* Don't call setup_coding_system for
5144 proc_decode_coding_system[channel] here. It is done in
5145 detect_coding called via decode_coding above. */
5146
5147 /* If a coding system for encoding is not yet decided, we set
5148 it as the same as coding-system for decoding.
5149
5150 But, before doing that we must check if
5151 proc_encode_coding_system[p->outfd] surely points to a
5152 valid memory because p->outfd will be changed once EOF is
5153 sent to the process. */
5154 if (NILP (p->encode_coding_system)
5155 && proc_encode_coding_system[p->outfd])
5156 {
5157 p->encode_coding_system
5158 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5159 setup_coding_system (p->encode_coding_system,
5160 proc_encode_coding_system[p->outfd]);
5161 }
5162 }
5163
5164 if (coding->carryover_bytes > 0)
5165 {
5166 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5167 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5168 bcopy (coding->carryover, SDATA (p->decoding_buf),
5169 coding->carryover_bytes);
5170 p->decoding_carryover = coding->carryover_bytes;
5171 }
5172 /* Adjust the multibyteness of TEXT to that of the filter. */
5173 if (!p->filter_multibyte != !STRING_MULTIBYTE (text))
5174 text = (STRING_MULTIBYTE (text)
5175 ? Fstring_as_unibyte (text)
5176 : Fstring_to_multibyte (text));
5177 if (SBYTES (text) > 0)
5178 internal_condition_case_1 (read_process_output_call,
5179 Fcons (outstream,
5180 Fcons (proc, Fcons (text, Qnil))),
5181 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5182 read_process_output_error_handler);
5183
5184 /* If we saved the match data nonrecursively, restore it now. */
5185 restore_search_regs ();
5186 running_asynch_code = outer_running_asynch_code;
5187
5188 /* Handling the process output should not deactivate the mark. */
5189 Vdeactivate_mark = odeactivate;
5190
5191 /* Restore waiting_for_user_input_p as it was
5192 when we were called, in case the filter clobbered it. */
5193 waiting_for_user_input_p = waiting;
5194
5195 #if 0 /* Call record_asynch_buffer_change unconditionally,
5196 because we might have changed minor modes or other things
5197 that affect key bindings. */
5198 if (! EQ (Fcurrent_buffer (), obuffer)
5199 || ! EQ (current_buffer->keymap, okeymap))
5200 #endif
5201 /* But do it only if the caller is actually going to read events.
5202 Otherwise there's no need to make him wake up, and it could
5203 cause trouble (for example it would make sit_for return). */
5204 if (waiting_for_user_input_p == -1)
5205 record_asynch_buffer_change ();
5206
5207 #ifdef VMS
5208 start_vms_process_read (vs);
5209 #endif
5210 unbind_to (count, Qnil);
5211 return nbytes;
5212 }
5213
5214 /* If no filter, write into buffer if it isn't dead. */
5215 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5216 {
5217 Lisp_Object old_read_only;
5218 int old_begv, old_zv;
5219 int old_begv_byte, old_zv_byte;
5220 Lisp_Object odeactivate;
5221 int before, before_byte;
5222 int opoint_byte;
5223 Lisp_Object text;
5224 struct buffer *b;
5225
5226 odeactivate = Vdeactivate_mark;
5227
5228 Fset_buffer (p->buffer);
5229 opoint = PT;
5230 opoint_byte = PT_BYTE;
5231 old_read_only = current_buffer->read_only;
5232 old_begv = BEGV;
5233 old_zv = ZV;
5234 old_begv_byte = BEGV_BYTE;
5235 old_zv_byte = ZV_BYTE;
5236
5237 current_buffer->read_only = Qnil;
5238
5239 /* Insert new output into buffer
5240 at the current end-of-output marker,
5241 thus preserving logical ordering of input and output. */
5242 if (XMARKER (p->mark)->buffer)
5243 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5244 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5245 ZV_BYTE));
5246 else
5247 SET_PT_BOTH (ZV, ZV_BYTE);
5248 before = PT;
5249 before_byte = PT_BYTE;
5250
5251 /* If the output marker is outside of the visible region, save
5252 the restriction and widen. */
5253 if (! (BEGV <= PT && PT <= ZV))
5254 Fwiden ();
5255
5256 decode_coding_c_string (coding, chars, nbytes, Qt);
5257 text = coding->dst_object;
5258 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5259 /* A new coding system might be found. See the comment in the
5260 similar code in the previous `if' block. */
5261 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5262 {
5263 p->decode_coding_system = Vlast_coding_system_used;
5264 if (NILP (p->encode_coding_system)
5265 && proc_encode_coding_system[p->outfd])
5266 {
5267 p->encode_coding_system
5268 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5269 setup_coding_system (p->encode_coding_system,
5270 proc_encode_coding_system[p->outfd]);
5271 }
5272 }
5273 if (coding->carryover_bytes > 0)
5274 {
5275 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5276 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5277 bcopy (coding->carryover, SDATA (p->decoding_buf),
5278 coding->carryover_bytes);
5279 p->decoding_carryover = coding->carryover_bytes;
5280 }
5281 /* Adjust the multibyteness of TEXT to that of the buffer. */
5282 if (NILP (current_buffer->enable_multibyte_characters)
5283 != ! STRING_MULTIBYTE (text))
5284 text = (STRING_MULTIBYTE (text)
5285 ? Fstring_as_unibyte (text)
5286 : Fstring_to_multibyte (text));
5287 /* Insert before markers in case we are inserting where
5288 the buffer's mark is, and the user's next command is Meta-y. */
5289 insert_from_string_before_markers (text, 0, 0,
5290 SCHARS (text), SBYTES (text), 0);
5291
5292 /* Make sure the process marker's position is valid when the
5293 process buffer is changed in the signal_after_change above.
5294 W3 is known to do that. */
5295 if (BUFFERP (p->buffer)
5296 && (b = XBUFFER (p->buffer), b != current_buffer))
5297 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5298 else
5299 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5300
5301 update_mode_lines++;
5302
5303 /* Make sure opoint and the old restrictions
5304 float ahead of any new text just as point would. */
5305 if (opoint >= before)
5306 {
5307 opoint += PT - before;
5308 opoint_byte += PT_BYTE - before_byte;
5309 }
5310 if (old_begv > before)
5311 {
5312 old_begv += PT - before;
5313 old_begv_byte += PT_BYTE - before_byte;
5314 }
5315 if (old_zv >= before)
5316 {
5317 old_zv += PT - before;
5318 old_zv_byte += PT_BYTE - before_byte;
5319 }
5320
5321 /* If the restriction isn't what it should be, set it. */
5322 if (old_begv != BEGV || old_zv != ZV)
5323 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5324
5325 /* Handling the process output should not deactivate the mark. */
5326 Vdeactivate_mark = odeactivate;
5327
5328 current_buffer->read_only = old_read_only;
5329 SET_PT_BOTH (opoint, opoint_byte);
5330 set_buffer_internal (old);
5331 }
5332 #ifdef VMS
5333 start_vms_process_read (vs);
5334 #endif
5335 return nbytes;
5336 }
5337
5338 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5339 0, 0, 0,
5340 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5341 This is intended for use by asynchronous process output filters and sentinels. */)
5342 ()
5343 {
5344 return (waiting_for_user_input_p ? Qt : Qnil);
5345 }
5346 \f
5347 /* Sending data to subprocess */
5348
5349 jmp_buf send_process_frame;
5350 Lisp_Object process_sent_to;
5351
5352 SIGTYPE
5353 send_process_trap ()
5354 {
5355 SIGNAL_THREAD_CHECK (SIGPIPE);
5356 #ifdef BSD4_1
5357 sigrelse (SIGPIPE);
5358 sigrelse (SIGALRM);
5359 #endif /* BSD4_1 */
5360 sigunblock (sigmask (SIGPIPE));
5361 longjmp (send_process_frame, 1);
5362 }
5363
5364 /* Send some data to process PROC.
5365 BUF is the beginning of the data; LEN is the number of characters.
5366 OBJECT is the Lisp object that the data comes from. If OBJECT is
5367 nil or t, it means that the data comes from C string.
5368
5369 If OBJECT is not nil, the data is encoded by PROC's coding-system
5370 for encoding before it is sent.
5371
5372 This function can evaluate Lisp code and can garbage collect. */
5373
5374 static void
5375 send_process (proc, buf, len, object)
5376 volatile Lisp_Object proc;
5377 unsigned char *volatile buf;
5378 volatile int len;
5379 volatile Lisp_Object object;
5380 {
5381 /* Use volatile to protect variables from being clobbered by longjmp. */
5382 struct Lisp_Process *p = XPROCESS (proc);
5383 int rv;
5384 struct coding_system *coding;
5385 struct gcpro gcpro1;
5386 SIGTYPE (*volatile old_sigpipe) ();
5387
5388 GCPRO1 (object);
5389
5390 #ifdef VMS
5391 VMS_PROC_STUFF *vs, *get_vms_process_pointer();
5392 #endif /* VMS */
5393
5394 if (p->raw_status_new)
5395 update_status (p);
5396 if (! EQ (p->status, Qrun))
5397 error ("Process %s not running", SDATA (p->name));
5398 if (p->outfd < 0)
5399 error ("Output file descriptor of %s is closed", SDATA (p->name));
5400
5401 coding = proc_encode_coding_system[p->outfd];
5402 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5403
5404 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5405 || (BUFFERP (object)
5406 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5407 || EQ (object, Qt))
5408 {
5409 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5410 /* The coding system for encoding was changed to raw-text
5411 because we sent a unibyte text previously. Now we are
5412 sending a multibyte text, thus we must encode it by the
5413 original coding system specified for the current process. */
5414 setup_coding_system (p->encode_coding_system, coding);
5415 coding->src_multibyte = 1;
5416 }
5417 else
5418 {
5419 /* For sending a unibyte text, character code conversion should
5420 not take place but EOL conversion should. So, setup raw-text
5421 or one of the subsidiary if we have not yet done it. */
5422 if (CODING_REQUIRE_ENCODING (coding))
5423 {
5424 if (CODING_REQUIRE_FLUSHING (coding))
5425 {
5426 /* But, before changing the coding, we must flush out data. */
5427 coding->mode |= CODING_MODE_LAST_BLOCK;
5428 send_process (proc, "", 0, Qt);
5429 coding->mode &= CODING_MODE_LAST_BLOCK;
5430 }
5431 setup_coding_system (raw_text_coding_system
5432 (Vlast_coding_system_used),
5433 coding);
5434 coding->src_multibyte = 0;
5435 }
5436 }
5437 coding->dst_multibyte = 0;
5438
5439 if (CODING_REQUIRE_ENCODING (coding))
5440 {
5441 coding->dst_object = Qt;
5442 if (BUFFERP (object))
5443 {
5444 int from_byte, from, to;
5445 int save_pt, save_pt_byte;
5446 struct buffer *cur = current_buffer;
5447
5448 set_buffer_internal (XBUFFER (object));
5449 save_pt = PT, save_pt_byte = PT_BYTE;
5450
5451 from_byte = PTR_BYTE_POS (buf);
5452 from = BYTE_TO_CHAR (from_byte);
5453 to = BYTE_TO_CHAR (from_byte + len);
5454 TEMP_SET_PT_BOTH (from, from_byte);
5455 encode_coding_object (coding, object, from, from_byte,
5456 to, from_byte + len, Qt);
5457 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5458 set_buffer_internal (cur);
5459 }
5460 else if (STRINGP (object))
5461 {
5462 encode_coding_string (coding, object, 1);
5463 }
5464 else
5465 {
5466 coding->dst_object = make_unibyte_string (buf, len);
5467 coding->produced = len;
5468 }
5469
5470 len = coding->produced;
5471 buf = SDATA (coding->dst_object);
5472 }
5473
5474 #ifdef VMS
5475 vs = get_vms_process_pointer (p->pid);
5476 if (vs == 0)
5477 error ("Could not find this process: %x", p->pid);
5478 else if (write_to_vms_process (vs, buf, len))
5479 ;
5480 #else /* not VMS */
5481
5482 if (pty_max_bytes == 0)
5483 {
5484 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5485 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5486 if (pty_max_bytes < 0)
5487 pty_max_bytes = 250;
5488 #else
5489 pty_max_bytes = 250;
5490 #endif
5491 /* Deduct one, to leave space for the eof. */
5492 pty_max_bytes--;
5493 }
5494
5495 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5496 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5497 when returning with longjmp despite being declared volatile. */
5498 if (!setjmp (send_process_frame))
5499 {
5500 process_sent_to = proc;
5501 while (len > 0)
5502 {
5503 int this = len;
5504
5505 /* Decide how much data we can send in one batch.
5506 Long lines need to be split into multiple batches. */
5507 if (p->pty_flag)
5508 {
5509 /* Starting this at zero is always correct when not the first
5510 iteration because the previous iteration ended by sending C-d.
5511 It may not be correct for the first iteration
5512 if a partial line was sent in a separate send_process call.
5513 If that proves worth handling, we need to save linepos
5514 in the process object. */
5515 int linepos = 0;
5516 unsigned char *ptr = (unsigned char *) buf;
5517 unsigned char *end = (unsigned char *) buf + len;
5518
5519 /* Scan through this text for a line that is too long. */
5520 while (ptr != end && linepos < pty_max_bytes)
5521 {
5522 if (*ptr == '\n')
5523 linepos = 0;
5524 else
5525 linepos++;
5526 ptr++;
5527 }
5528 /* If we found one, break the line there
5529 and put in a C-d to force the buffer through. */
5530 this = ptr - buf;
5531 }
5532
5533 /* Send this batch, using one or more write calls. */
5534 while (this > 0)
5535 {
5536 int outfd = p->outfd;
5537 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5538 #ifdef DATAGRAM_SOCKETS
5539 if (DATAGRAM_CHAN_P (outfd))
5540 {
5541 rv = sendto (outfd, (char *) buf, this,
5542 0, datagram_address[outfd].sa,
5543 datagram_address[outfd].len);
5544 if (rv < 0 && errno == EMSGSIZE)
5545 {
5546 signal (SIGPIPE, old_sigpipe);
5547 report_file_error ("sending datagram",
5548 Fcons (proc, Qnil));
5549 }
5550 }
5551 else
5552 #endif
5553 {
5554 rv = emacs_write (outfd, (char *) buf, this);
5555 #ifdef ADAPTIVE_READ_BUFFERING
5556 if (p->read_output_delay > 0
5557 && p->adaptive_read_buffering == 1)
5558 {
5559 p->read_output_delay = 0;
5560 process_output_delay_count--;
5561 p->read_output_skip = 0;
5562 }
5563 #endif
5564 }
5565 signal (SIGPIPE, old_sigpipe);
5566
5567 if (rv < 0)
5568 {
5569 if (0
5570 #ifdef EWOULDBLOCK
5571 || errno == EWOULDBLOCK
5572 #endif
5573 #ifdef EAGAIN
5574 || errno == EAGAIN
5575 #endif
5576 )
5577 /* Buffer is full. Wait, accepting input;
5578 that may allow the program
5579 to finish doing output and read more. */
5580 {
5581 int offset = 0;
5582
5583 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5584 /* A gross hack to work around a bug in FreeBSD.
5585 In the following sequence, read(2) returns
5586 bogus data:
5587
5588 write(2) 1022 bytes
5589 write(2) 954 bytes, get EAGAIN
5590 read(2) 1024 bytes in process_read_output
5591 read(2) 11 bytes in process_read_output
5592
5593 That is, read(2) returns more bytes than have
5594 ever been written successfully. The 1033 bytes
5595 read are the 1022 bytes written successfully
5596 after processing (for example with CRs added if
5597 the terminal is set up that way which it is
5598 here). The same bytes will be seen again in a
5599 later read(2), without the CRs. */
5600
5601 if (errno == EAGAIN)
5602 {
5603 int flags = FWRITE;
5604 ioctl (p->outfd, TIOCFLUSH, &flags);
5605 }
5606 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5607
5608 /* Running filters might relocate buffers or strings.
5609 Arrange to relocate BUF. */
5610 if (BUFFERP (object))
5611 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5612 else if (STRINGP (object))
5613 offset = buf - SDATA (object);
5614
5615 #ifdef EMACS_HAS_USECS
5616 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5617 #else
5618 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5619 #endif
5620
5621 if (BUFFERP (object))
5622 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5623 else if (STRINGP (object))
5624 buf = offset + SDATA (object);
5625
5626 rv = 0;
5627 }
5628 else
5629 /* This is a real error. */
5630 report_file_error ("writing to process", Fcons (proc, Qnil));
5631 }
5632 buf += rv;
5633 len -= rv;
5634 this -= rv;
5635 }
5636
5637 /* If we sent just part of the string, put in an EOF
5638 to force it through, before we send the rest. */
5639 if (len > 0)
5640 Fprocess_send_eof (proc);
5641 }
5642 }
5643 #endif /* not VMS */
5644 else
5645 {
5646 signal (SIGPIPE, old_sigpipe);
5647 #ifndef VMS
5648 proc = process_sent_to;
5649 p = XPROCESS (proc);
5650 #endif
5651 p->raw_status_new = 0;
5652 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5653 p->tick = ++process_tick;
5654 deactivate_process (proc);
5655 #ifdef VMS
5656 error ("Error writing to process %s; closed it", SDATA (p->name));
5657 #else
5658 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5659 #endif
5660 }
5661
5662 UNGCPRO;
5663 }
5664
5665 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5666 3, 3, 0,
5667 doc: /* Send current contents of region as input to PROCESS.
5668 PROCESS may be a process, a buffer, the name of a process or buffer, or
5669 nil, indicating the current buffer's process.
5670 Called from program, takes three arguments, PROCESS, START and END.
5671 If the region is more than 500 characters long,
5672 it is sent in several bunches. This may happen even for shorter regions.
5673 Output from processes can arrive in between bunches. */)
5674 (process, start, end)
5675 Lisp_Object process, start, end;
5676 {
5677 Lisp_Object proc;
5678 int start1, end1;
5679
5680 proc = get_process (process);
5681 validate_region (&start, &end);
5682
5683 if (XINT (start) < GPT && XINT (end) > GPT)
5684 move_gap (XINT (start));
5685
5686 start1 = CHAR_TO_BYTE (XINT (start));
5687 end1 = CHAR_TO_BYTE (XINT (end));
5688 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5689 Fcurrent_buffer ());
5690
5691 return Qnil;
5692 }
5693
5694 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5695 2, 2, 0,
5696 doc: /* Send PROCESS the contents of STRING as input.
5697 PROCESS may be a process, a buffer, the name of a process or buffer, or
5698 nil, indicating the current buffer's process.
5699 If STRING is more than 500 characters long,
5700 it is sent in several bunches. This may happen even for shorter strings.
5701 Output from processes can arrive in between bunches. */)
5702 (process, string)
5703 Lisp_Object process, string;
5704 {
5705 Lisp_Object proc;
5706 CHECK_STRING (string);
5707 proc = get_process (process);
5708 send_process (proc, SDATA (string),
5709 SBYTES (string), string);
5710 return Qnil;
5711 }
5712 \f
5713 /* Return the foreground process group for the tty/pty that
5714 the process P uses. */
5715 static int
5716 emacs_get_tty_pgrp (p)
5717 struct Lisp_Process *p;
5718 {
5719 int gid = -1;
5720
5721 #ifdef TIOCGPGRP
5722 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5723 {
5724 int fd;
5725 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5726 master side. Try the slave side. */
5727 fd = emacs_open (XSTRING (p->tty_name)->data, O_RDONLY, 0);
5728
5729 if (fd != -1)
5730 {
5731 ioctl (fd, TIOCGPGRP, &gid);
5732 emacs_close (fd);
5733 }
5734 }
5735 #endif /* defined (TIOCGPGRP ) */
5736
5737 return gid;
5738 }
5739
5740 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5741 Sprocess_running_child_p, 0, 1, 0,
5742 doc: /* Return t if PROCESS has given the terminal to a child.
5743 If the operating system does not make it possible to find out,
5744 return t unconditionally. */)
5745 (process)
5746 Lisp_Object process;
5747 {
5748 /* Initialize in case ioctl doesn't exist or gives an error,
5749 in a way that will cause returning t. */
5750 int gid;
5751 Lisp_Object proc;
5752 struct Lisp_Process *p;
5753
5754 proc = get_process (process);
5755 p = XPROCESS (proc);
5756
5757 if (!EQ (p->childp, Qt))
5758 error ("Process %s is not a subprocess",
5759 SDATA (p->name));
5760 if (p->infd < 0)
5761 error ("Process %s is not active",
5762 SDATA (p->name));
5763
5764 gid = emacs_get_tty_pgrp (p);
5765
5766 if (gid == p->pid)
5767 return Qnil;
5768 return Qt;
5769 }
5770 \f
5771 /* send a signal number SIGNO to PROCESS.
5772 If CURRENT_GROUP is t, that means send to the process group
5773 that currently owns the terminal being used to communicate with PROCESS.
5774 This is used for various commands in shell mode.
5775 If CURRENT_GROUP is lambda, that means send to the process group
5776 that currently owns the terminal, but only if it is NOT the shell itself.
5777
5778 If NOMSG is zero, insert signal-announcements into process's buffers
5779 right away.
5780
5781 If we can, we try to signal PROCESS by sending control characters
5782 down the pty. This allows us to signal inferiors who have changed
5783 their uid, for which killpg would return an EPERM error. */
5784
5785 static void
5786 process_send_signal (process, signo, current_group, nomsg)
5787 Lisp_Object process;
5788 int signo;
5789 Lisp_Object current_group;
5790 int nomsg;
5791 {
5792 Lisp_Object proc;
5793 register struct Lisp_Process *p;
5794 int gid;
5795 int no_pgrp = 0;
5796
5797 proc = get_process (process);
5798 p = XPROCESS (proc);
5799
5800 if (!EQ (p->childp, Qt))
5801 error ("Process %s is not a subprocess",
5802 SDATA (p->name));
5803 if (p->infd < 0)
5804 error ("Process %s is not active",
5805 SDATA (p->name));
5806
5807 if (!p->pty_flag)
5808 current_group = Qnil;
5809
5810 /* If we are using pgrps, get a pgrp number and make it negative. */
5811 if (NILP (current_group))
5812 /* Send the signal to the shell's process group. */
5813 gid = p->pid;
5814 else
5815 {
5816 #ifdef SIGNALS_VIA_CHARACTERS
5817 /* If possible, send signals to the entire pgrp
5818 by sending an input character to it. */
5819
5820 /* TERMIOS is the latest and bestest, and seems most likely to
5821 work. If the system has it, use it. */
5822 #ifdef HAVE_TERMIOS
5823 struct termios t;
5824 cc_t *sig_char = NULL;
5825
5826 tcgetattr (p->infd, &t);
5827
5828 switch (signo)
5829 {
5830 case SIGINT:
5831 sig_char = &t.c_cc[VINTR];
5832 break;
5833
5834 case SIGQUIT:
5835 sig_char = &t.c_cc[VQUIT];
5836 break;
5837
5838 case SIGTSTP:
5839 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5840 sig_char = &t.c_cc[VSWTCH];
5841 #else
5842 sig_char = &t.c_cc[VSUSP];
5843 #endif
5844 break;
5845 }
5846
5847 if (sig_char && *sig_char != CDISABLE)
5848 {
5849 send_process (proc, sig_char, 1, Qnil);
5850 return;
5851 }
5852 /* If we can't send the signal with a character,
5853 fall through and send it another way. */
5854 #else /* ! HAVE_TERMIOS */
5855
5856 /* On Berkeley descendants, the following IOCTL's retrieve the
5857 current control characters. */
5858 #if defined (TIOCGLTC) && defined (TIOCGETC)
5859
5860 struct tchars c;
5861 struct ltchars lc;
5862
5863 switch (signo)
5864 {
5865 case SIGINT:
5866 ioctl (p->infd, TIOCGETC, &c);
5867 send_process (proc, &c.t_intrc, 1, Qnil);
5868 return;
5869 case SIGQUIT:
5870 ioctl (p->infd, TIOCGETC, &c);
5871 send_process (proc, &c.t_quitc, 1, Qnil);
5872 return;
5873 #ifdef SIGTSTP
5874 case SIGTSTP:
5875 ioctl (p->infd, TIOCGLTC, &lc);
5876 send_process (proc, &lc.t_suspc, 1, Qnil);
5877 return;
5878 #endif /* ! defined (SIGTSTP) */
5879 }
5880
5881 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5882
5883 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
5884 characters. */
5885 #ifdef TCGETA
5886 struct termio t;
5887 switch (signo)
5888 {
5889 case SIGINT:
5890 ioctl (p->infd, TCGETA, &t);
5891 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
5892 return;
5893 case SIGQUIT:
5894 ioctl (p->infd, TCGETA, &t);
5895 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
5896 return;
5897 #ifdef SIGTSTP
5898 case SIGTSTP:
5899 ioctl (p->infd, TCGETA, &t);
5900 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
5901 return;
5902 #endif /* ! defined (SIGTSTP) */
5903 }
5904 #else /* ! defined (TCGETA) */
5905 Your configuration files are messed up.
5906 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
5907 you'd better be using one of the alternatives above! */
5908 #endif /* ! defined (TCGETA) */
5909 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
5910 /* In this case, the code above should alway returns. */
5911 abort ();
5912 #endif /* ! defined HAVE_TERMIOS */
5913
5914 /* The code above may fall through if it can't
5915 handle the signal. */
5916 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
5917
5918 #ifdef TIOCGPGRP
5919 /* Get the current pgrp using the tty itself, if we have that.
5920 Otherwise, use the pty to get the pgrp.
5921 On pfa systems, saka@pfu.fujitsu.co.JP writes:
5922 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
5923 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
5924 His patch indicates that if TIOCGPGRP returns an error, then
5925 we should just assume that p->pid is also the process group id. */
5926
5927 gid = emacs_get_tty_pgrp (p);
5928
5929 if (gid == -1)
5930 /* If we can't get the information, assume
5931 the shell owns the tty. */
5932 gid = p->pid;
5933
5934 /* It is not clear whether anything really can set GID to -1.
5935 Perhaps on some system one of those ioctls can or could do so.
5936 Or perhaps this is vestigial. */
5937 if (gid == -1)
5938 no_pgrp = 1;
5939 #else /* ! defined (TIOCGPGRP ) */
5940 /* Can't select pgrps on this system, so we know that
5941 the child itself heads the pgrp. */
5942 gid = p->pid;
5943 #endif /* ! defined (TIOCGPGRP ) */
5944
5945 /* If current_group is lambda, and the shell owns the terminal,
5946 don't send any signal. */
5947 if (EQ (current_group, Qlambda) && gid == p->pid)
5948 return;
5949 }
5950
5951 switch (signo)
5952 {
5953 #ifdef SIGCONT
5954 case SIGCONT:
5955 p->raw_status_new = 0;
5956 p->status = Qrun;
5957 p->tick = ++process_tick;
5958 if (!nomsg)
5959 status_notify (NULL);
5960 break;
5961 #endif /* ! defined (SIGCONT) */
5962 case SIGINT:
5963 #ifdef VMS
5964 send_process (proc, "\003", 1, Qnil); /* ^C */
5965 goto whoosh;
5966 #endif
5967 case SIGQUIT:
5968 #ifdef VMS
5969 send_process (proc, "\031", 1, Qnil); /* ^Y */
5970 goto whoosh;
5971 #endif
5972 case SIGKILL:
5973 #ifdef VMS
5974 sys$forcex (&(p->pid), 0, 1);
5975 whoosh:
5976 #endif
5977 flush_pending_output (p->infd);
5978 break;
5979 }
5980
5981 /* If we don't have process groups, send the signal to the immediate
5982 subprocess. That isn't really right, but it's better than any
5983 obvious alternative. */
5984 if (no_pgrp)
5985 {
5986 kill (p->pid, signo);
5987 return;
5988 }
5989
5990 /* gid may be a pid, or minus a pgrp's number */
5991 #ifdef TIOCSIGSEND
5992 if (!NILP (current_group))
5993 {
5994 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
5995 EMACS_KILLPG (gid, signo);
5996 }
5997 else
5998 {
5999 gid = - p->pid;
6000 kill (gid, signo);
6001 }
6002 #else /* ! defined (TIOCSIGSEND) */
6003 EMACS_KILLPG (gid, signo);
6004 #endif /* ! defined (TIOCSIGSEND) */
6005 }
6006
6007 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6008 doc: /* Interrupt process PROCESS.
6009 PROCESS may be a process, a buffer, or the name of a process or buffer.
6010 No arg or nil means current buffer's process.
6011 Second arg CURRENT-GROUP non-nil means send signal to
6012 the current process-group of the process's controlling terminal
6013 rather than to the process's own process group.
6014 If the process is a shell, this means interrupt current subjob
6015 rather than the shell.
6016
6017 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6018 don't send the signal. */)
6019 (process, current_group)
6020 Lisp_Object process, current_group;
6021 {
6022 process_send_signal (process, SIGINT, current_group, 0);
6023 return process;
6024 }
6025
6026 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6027 doc: /* Kill process PROCESS. May be process or name of one.
6028 See function `interrupt-process' for more details on usage. */)
6029 (process, current_group)
6030 Lisp_Object process, current_group;
6031 {
6032 process_send_signal (process, SIGKILL, current_group, 0);
6033 return process;
6034 }
6035
6036 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6037 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6038 See function `interrupt-process' for more details on usage. */)
6039 (process, current_group)
6040 Lisp_Object process, current_group;
6041 {
6042 process_send_signal (process, SIGQUIT, current_group, 0);
6043 return process;
6044 }
6045
6046 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6047 doc: /* Stop process PROCESS. May be process or name of one.
6048 See function `interrupt-process' for more details on usage.
6049 If PROCESS is a network process, inhibit handling of incoming traffic. */)
6050 (process, current_group)
6051 Lisp_Object process, current_group;
6052 {
6053 #ifdef HAVE_SOCKETS
6054 if (PROCESSP (process) && NETCONN_P (process))
6055 {
6056 struct Lisp_Process *p;
6057
6058 p = XPROCESS (process);
6059 if (NILP (p->command)
6060 && p->infd >= 0)
6061 {
6062 FD_CLR (p->infd, &input_wait_mask);
6063 FD_CLR (p->infd, &non_keyboard_wait_mask);
6064 }
6065 p->command = Qt;
6066 return process;
6067 }
6068 #endif
6069 #ifndef SIGTSTP
6070 error ("No SIGTSTP support");
6071 #else
6072 process_send_signal (process, SIGTSTP, current_group, 0);
6073 #endif
6074 return process;
6075 }
6076
6077 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6078 doc: /* Continue process PROCESS. May be process or name of one.
6079 See function `interrupt-process' for more details on usage.
6080 If PROCESS is a network process, resume handling of incoming traffic. */)
6081 (process, current_group)
6082 Lisp_Object process, current_group;
6083 {
6084 #ifdef HAVE_SOCKETS
6085 if (PROCESSP (process) && NETCONN_P (process))
6086 {
6087 struct Lisp_Process *p;
6088
6089 p = XPROCESS (process);
6090 if (EQ (p->command, Qt)
6091 && p->infd >= 0
6092 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6093 {
6094 FD_SET (p->infd, &input_wait_mask);
6095 FD_SET (p->infd, &non_keyboard_wait_mask);
6096 }
6097 p->command = Qnil;
6098 return process;
6099 }
6100 #endif
6101 #ifdef SIGCONT
6102 process_send_signal (process, SIGCONT, current_group, 0);
6103 #else
6104 error ("No SIGCONT support");
6105 #endif
6106 return process;
6107 }
6108
6109 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6110 2, 2, "sProcess (name or number): \nnSignal code: ",
6111 doc: /* Send PROCESS the signal with code SIGCODE.
6112 PROCESS may also be a number specifying the process id of the
6113 process to signal; in this case, the process need not be a child of
6114 this Emacs.
6115 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6116 (process, sigcode)
6117 Lisp_Object process, sigcode;
6118 {
6119 pid_t pid;
6120
6121 if (INTEGERP (process))
6122 {
6123 pid = XINT (process);
6124 goto got_it;
6125 }
6126
6127 if (FLOATP (process))
6128 {
6129 pid = (pid_t) XFLOAT_DATA (process);
6130 goto got_it;
6131 }
6132
6133 if (STRINGP (process))
6134 {
6135 Lisp_Object tem;
6136 if (tem = Fget_process (process), NILP (tem))
6137 {
6138 pid = XINT (Fstring_to_number (process, make_number (10)));
6139 if (pid > 0)
6140 goto got_it;
6141 }
6142 process = tem;
6143 }
6144 else
6145 process = get_process (process);
6146
6147 if (NILP (process))
6148 return process;
6149
6150 CHECK_PROCESS (process);
6151 pid = XPROCESS (process)->pid;
6152 if (pid <= 0)
6153 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6154
6155 got_it:
6156
6157 #define parse_signal(NAME, VALUE) \
6158 else if (!xstricmp (name, NAME)) \
6159 XSETINT (sigcode, VALUE)
6160
6161 if (INTEGERP (sigcode))
6162 ;
6163 else
6164 {
6165 unsigned char *name;
6166
6167 CHECK_SYMBOL (sigcode);
6168 name = SDATA (SYMBOL_NAME (sigcode));
6169
6170 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6171 name += 3;
6172
6173 if (0)
6174 ;
6175 #ifdef SIGUSR1
6176 parse_signal ("usr1", SIGUSR1);
6177 #endif
6178 #ifdef SIGUSR2
6179 parse_signal ("usr2", SIGUSR2);
6180 #endif
6181 #ifdef SIGTERM
6182 parse_signal ("term", SIGTERM);
6183 #endif
6184 #ifdef SIGHUP
6185 parse_signal ("hup", SIGHUP);
6186 #endif
6187 #ifdef SIGINT
6188 parse_signal ("int", SIGINT);
6189 #endif
6190 #ifdef SIGQUIT
6191 parse_signal ("quit", SIGQUIT);
6192 #endif
6193 #ifdef SIGILL
6194 parse_signal ("ill", SIGILL);
6195 #endif
6196 #ifdef SIGABRT
6197 parse_signal ("abrt", SIGABRT);
6198 #endif
6199 #ifdef SIGEMT
6200 parse_signal ("emt", SIGEMT);
6201 #endif
6202 #ifdef SIGKILL
6203 parse_signal ("kill", SIGKILL);
6204 #endif
6205 #ifdef SIGFPE
6206 parse_signal ("fpe", SIGFPE);
6207 #endif
6208 #ifdef SIGBUS
6209 parse_signal ("bus", SIGBUS);
6210 #endif
6211 #ifdef SIGSEGV
6212 parse_signal ("segv", SIGSEGV);
6213 #endif
6214 #ifdef SIGSYS
6215 parse_signal ("sys", SIGSYS);
6216 #endif
6217 #ifdef SIGPIPE
6218 parse_signal ("pipe", SIGPIPE);
6219 #endif
6220 #ifdef SIGALRM
6221 parse_signal ("alrm", SIGALRM);
6222 #endif
6223 #ifdef SIGURG
6224 parse_signal ("urg", SIGURG);
6225 #endif
6226 #ifdef SIGSTOP
6227 parse_signal ("stop", SIGSTOP);
6228 #endif
6229 #ifdef SIGTSTP
6230 parse_signal ("tstp", SIGTSTP);
6231 #endif
6232 #ifdef SIGCONT
6233 parse_signal ("cont", SIGCONT);
6234 #endif
6235 #ifdef SIGCHLD
6236 parse_signal ("chld", SIGCHLD);
6237 #endif
6238 #ifdef SIGTTIN
6239 parse_signal ("ttin", SIGTTIN);
6240 #endif
6241 #ifdef SIGTTOU
6242 parse_signal ("ttou", SIGTTOU);
6243 #endif
6244 #ifdef SIGIO
6245 parse_signal ("io", SIGIO);
6246 #endif
6247 #ifdef SIGXCPU
6248 parse_signal ("xcpu", SIGXCPU);
6249 #endif
6250 #ifdef SIGXFSZ
6251 parse_signal ("xfsz", SIGXFSZ);
6252 #endif
6253 #ifdef SIGVTALRM
6254 parse_signal ("vtalrm", SIGVTALRM);
6255 #endif
6256 #ifdef SIGPROF
6257 parse_signal ("prof", SIGPROF);
6258 #endif
6259 #ifdef SIGWINCH
6260 parse_signal ("winch", SIGWINCH);
6261 #endif
6262 #ifdef SIGINFO
6263 parse_signal ("info", SIGINFO);
6264 #endif
6265 else
6266 error ("Undefined signal name %s", name);
6267 }
6268
6269 #undef parse_signal
6270
6271 return make_number (kill (pid, XINT (sigcode)));
6272 }
6273
6274 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6275 doc: /* Make PROCESS see end-of-file in its input.
6276 EOF comes after any text already sent to it.
6277 PROCESS may be a process, a buffer, the name of a process or buffer, or
6278 nil, indicating the current buffer's process.
6279 If PROCESS is a network connection, or is a process communicating
6280 through a pipe (as opposed to a pty), then you cannot send any more
6281 text to PROCESS after you call this function. */)
6282 (process)
6283 Lisp_Object process;
6284 {
6285 Lisp_Object proc;
6286 struct coding_system *coding;
6287
6288 if (DATAGRAM_CONN_P (process))
6289 return process;
6290
6291 proc = get_process (process);
6292 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6293
6294 /* Make sure the process is really alive. */
6295 if (XPROCESS (proc)->raw_status_new)
6296 update_status (XPROCESS (proc));
6297 if (! EQ (XPROCESS (proc)->status, Qrun))
6298 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6299
6300 if (CODING_REQUIRE_FLUSHING (coding))
6301 {
6302 coding->mode |= CODING_MODE_LAST_BLOCK;
6303 send_process (proc, "", 0, Qnil);
6304 }
6305
6306 #ifdef VMS
6307 send_process (proc, "\032", 1, Qnil); /* ^z */
6308 #else
6309 if (XPROCESS (proc)->pty_flag)
6310 send_process (proc, "\004", 1, Qnil);
6311 else
6312 {
6313 int old_outfd, new_outfd;
6314
6315 #ifdef HAVE_SHUTDOWN
6316 /* If this is a network connection, or socketpair is used
6317 for communication with the subprocess, call shutdown to cause EOF.
6318 (In some old system, shutdown to socketpair doesn't work.
6319 Then we just can't win.) */
6320 if (XPROCESS (proc)->pid == 0
6321 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6322 shutdown (XPROCESS (proc)->outfd, 1);
6323 /* In case of socketpair, outfd == infd, so don't close it. */
6324 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6325 emacs_close (XPROCESS (proc)->outfd);
6326 #else /* not HAVE_SHUTDOWN */
6327 emacs_close (XPROCESS (proc)->outfd);
6328 #endif /* not HAVE_SHUTDOWN */
6329 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6330 if (new_outfd < 0)
6331 abort ();
6332 old_outfd = XPROCESS (proc)->outfd;
6333
6334 if (!proc_encode_coding_system[new_outfd])
6335 proc_encode_coding_system[new_outfd]
6336 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6337 bcopy (proc_encode_coding_system[old_outfd],
6338 proc_encode_coding_system[new_outfd],
6339 sizeof (struct coding_system));
6340 bzero (proc_encode_coding_system[old_outfd],
6341 sizeof (struct coding_system));
6342
6343 XPROCESS (proc)->outfd = new_outfd;
6344 }
6345 #endif /* VMS */
6346 return process;
6347 }
6348
6349 /* Kill all processes associated with `buffer'.
6350 If `buffer' is nil, kill all processes */
6351
6352 void
6353 kill_buffer_processes (buffer)
6354 Lisp_Object buffer;
6355 {
6356 Lisp_Object tail, proc;
6357
6358 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6359 {
6360 proc = XCDR (XCAR (tail));
6361 if (PROCESSP (proc)
6362 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6363 {
6364 if (NETCONN_P (proc))
6365 Fdelete_process (proc);
6366 else if (XPROCESS (proc)->infd >= 0)
6367 process_send_signal (proc, SIGHUP, Qnil, 1);
6368 }
6369 }
6370 }
6371 \f
6372 /* On receipt of a signal that a child status has changed, loop asking
6373 about children with changed statuses until the system says there
6374 are no more.
6375
6376 All we do is change the status; we do not run sentinels or print
6377 notifications. That is saved for the next time keyboard input is
6378 done, in order to avoid timing errors.
6379
6380 ** WARNING: this can be called during garbage collection.
6381 Therefore, it must not be fooled by the presence of mark bits in
6382 Lisp objects.
6383
6384 ** USG WARNING: Although it is not obvious from the documentation
6385 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6386 signal() before executing at least one wait(), otherwise the
6387 handler will be called again, resulting in an infinite loop. The
6388 relevant portion of the documentation reads "SIGCLD signals will be
6389 queued and the signal-catching function will be continually
6390 reentered until the queue is empty". Invoking signal() causes the
6391 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6392 Inc.
6393
6394 ** Malloc WARNING: This should never call malloc either directly or
6395 indirectly; if it does, that is a bug */
6396
6397 #ifdef SIGCHLD
6398 SIGTYPE
6399 sigchld_handler (signo)
6400 int signo;
6401 {
6402 int old_errno = errno;
6403 Lisp_Object proc;
6404 register struct Lisp_Process *p;
6405 extern EMACS_TIME *input_available_clear_time;
6406
6407 SIGNAL_THREAD_CHECK (signo);
6408
6409 #ifdef BSD4_1
6410 extern int sigheld;
6411 sigheld |= sigbit (SIGCHLD);
6412 #endif
6413
6414 while (1)
6415 {
6416 pid_t pid;
6417 WAITTYPE w;
6418 Lisp_Object tail;
6419
6420 #ifdef WNOHANG
6421 #ifndef WUNTRACED
6422 #define WUNTRACED 0
6423 #endif /* no WUNTRACED */
6424 /* Keep trying to get a status until we get a definitive result. */
6425 do
6426 {
6427 errno = 0;
6428 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6429 }
6430 while (pid < 0 && errno == EINTR);
6431
6432 if (pid <= 0)
6433 {
6434 /* PID == 0 means no processes found, PID == -1 means a real
6435 failure. We have done all our job, so return. */
6436
6437 /* USG systems forget handlers when they are used;
6438 must reestablish each time */
6439 #if defined (USG) && !defined (POSIX_SIGNALS)
6440 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6441 #endif
6442 #ifdef BSD4_1
6443 sigheld &= ~sigbit (SIGCHLD);
6444 sigrelse (SIGCHLD);
6445 #endif
6446 errno = old_errno;
6447 return;
6448 }
6449 #else
6450 pid = wait (&w);
6451 #endif /* no WNOHANG */
6452
6453 /* Find the process that signaled us, and record its status. */
6454
6455 /* The process can have been deleted by Fdelete_process. */
6456 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6457 {
6458 Lisp_Object xpid = XCAR (tail);
6459 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6460 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6461 {
6462 XSETCAR (tail, Qnil);
6463 goto sigchld_end_of_loop;
6464 }
6465 }
6466
6467 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6468 p = 0;
6469 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6470 {
6471 proc = XCDR (XCAR (tail));
6472 p = XPROCESS (proc);
6473 if (EQ (p->childp, Qt) && p->pid == pid)
6474 break;
6475 p = 0;
6476 }
6477
6478 /* Look for an asynchronous process whose pid hasn't been filled
6479 in yet. */
6480 if (p == 0)
6481 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6482 {
6483 proc = XCDR (XCAR (tail));
6484 p = XPROCESS (proc);
6485 if (p->pid == -1)
6486 break;
6487 p = 0;
6488 }
6489
6490 /* Change the status of the process that was found. */
6491 if (p != 0)
6492 {
6493 union { int i; WAITTYPE wt; } u;
6494 int clear_desc_flag = 0;
6495
6496 p->tick = ++process_tick;
6497 u.wt = w;
6498 p->raw_status = u.i;
6499 p->raw_status_new = 1;
6500
6501 /* If process has terminated, stop waiting for its output. */
6502 if ((WIFSIGNALED (w) || WIFEXITED (w))
6503 && p->infd >= 0)
6504 clear_desc_flag = 1;
6505
6506 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6507 if (clear_desc_flag)
6508 {
6509 FD_CLR (p->infd, &input_wait_mask);
6510 FD_CLR (p->infd, &non_keyboard_wait_mask);
6511 }
6512
6513 /* Tell wait_reading_process_output that it needs to wake up and
6514 look around. */
6515 if (input_available_clear_time)
6516 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6517 }
6518
6519 /* There was no asynchronous process found for that pid: we have
6520 a synchronous process. */
6521 else
6522 {
6523 synch_process_alive = 0;
6524
6525 /* Report the status of the synchronous process. */
6526 if (WIFEXITED (w))
6527 synch_process_retcode = WRETCODE (w);
6528 else if (WIFSIGNALED (w))
6529 synch_process_termsig = WTERMSIG (w);
6530
6531 /* Tell wait_reading_process_output that it needs to wake up and
6532 look around. */
6533 if (input_available_clear_time)
6534 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6535 }
6536
6537 sigchld_end_of_loop:
6538 ;
6539
6540 /* On some systems, we must return right away.
6541 If any more processes want to signal us, we will
6542 get another signal.
6543 Otherwise (on systems that have WNOHANG), loop around
6544 to use up all the processes that have something to tell us. */
6545 #if (defined WINDOWSNT \
6546 || (defined USG && !defined GNU_LINUX \
6547 && !(defined HPUX && defined WNOHANG)))
6548 #if defined (USG) && ! defined (POSIX_SIGNALS)
6549 signal (signo, sigchld_handler);
6550 #endif
6551 errno = old_errno;
6552 return;
6553 #endif /* USG, but not HPUX with WNOHANG */
6554 }
6555 }
6556 #endif /* SIGCHLD */
6557 \f
6558
6559 static Lisp_Object
6560 exec_sentinel_unwind (data)
6561 Lisp_Object data;
6562 {
6563 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6564 return Qnil;
6565 }
6566
6567 static Lisp_Object
6568 exec_sentinel_error_handler (error)
6569 Lisp_Object error;
6570 {
6571 cmd_error_internal (error, "error in process sentinel: ");
6572 Vinhibit_quit = Qt;
6573 update_echo_area ();
6574 Fsleep_for (make_number (2), Qnil);
6575 return Qt;
6576 }
6577
6578 static void
6579 exec_sentinel (proc, reason)
6580 Lisp_Object proc, reason;
6581 {
6582 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6583 register struct Lisp_Process *p = XPROCESS (proc);
6584 int count = SPECPDL_INDEX ();
6585 int outer_running_asynch_code = running_asynch_code;
6586 int waiting = waiting_for_user_input_p;
6587
6588 if (inhibit_sentinels)
6589 return;
6590
6591 /* No need to gcpro these, because all we do with them later
6592 is test them for EQness, and none of them should be a string. */
6593 odeactivate = Vdeactivate_mark;
6594 XSETBUFFER (obuffer, current_buffer);
6595 okeymap = current_buffer->keymap;
6596
6597 sentinel = p->sentinel;
6598 if (NILP (sentinel))
6599 return;
6600
6601 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6602 assure that it gets restored no matter how the sentinel exits. */
6603 p->sentinel = Qnil;
6604 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6605 /* Inhibit quit so that random quits don't screw up a running filter. */
6606 specbind (Qinhibit_quit, Qt);
6607 specbind (Qlast_nonmenu_event, Qt);
6608
6609 /* In case we get recursively called,
6610 and we already saved the match data nonrecursively,
6611 save the same match data in safely recursive fashion. */
6612 if (outer_running_asynch_code)
6613 {
6614 Lisp_Object tem;
6615 tem = Fmatch_data (Qnil, Qnil, Qnil);
6616 restore_search_regs ();
6617 record_unwind_save_match_data ();
6618 Fset_match_data (tem, Qt);
6619 }
6620
6621 /* For speed, if a search happens within this code,
6622 save the match data in a special nonrecursive fashion. */
6623 running_asynch_code = 1;
6624
6625 internal_condition_case_1 (read_process_output_call,
6626 Fcons (sentinel,
6627 Fcons (proc, Fcons (reason, Qnil))),
6628 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6629 exec_sentinel_error_handler);
6630
6631 /* If we saved the match data nonrecursively, restore it now. */
6632 restore_search_regs ();
6633 running_asynch_code = outer_running_asynch_code;
6634
6635 Vdeactivate_mark = odeactivate;
6636
6637 /* Restore waiting_for_user_input_p as it was
6638 when we were called, in case the filter clobbered it. */
6639 waiting_for_user_input_p = waiting;
6640
6641 #if 0
6642 if (! EQ (Fcurrent_buffer (), obuffer)
6643 || ! EQ (current_buffer->keymap, okeymap))
6644 #endif
6645 /* But do it only if the caller is actually going to read events.
6646 Otherwise there's no need to make him wake up, and it could
6647 cause trouble (for example it would make sit_for return). */
6648 if (waiting_for_user_input_p == -1)
6649 record_asynch_buffer_change ();
6650
6651 unbind_to (count, Qnil);
6652 }
6653
6654 /* Report all recent events of a change in process status
6655 (either run the sentinel or output a message).
6656 This is usually done while Emacs is waiting for keyboard input
6657 but can be done at other times. */
6658
6659 static void
6660 status_notify (deleting_process)
6661 struct Lisp_Process *deleting_process;
6662 {
6663 register Lisp_Object proc, buffer;
6664 Lisp_Object tail, msg;
6665 struct gcpro gcpro1, gcpro2;
6666
6667 tail = Qnil;
6668 msg = Qnil;
6669 /* We need to gcpro tail; if read_process_output calls a filter
6670 which deletes a process and removes the cons to which tail points
6671 from Vprocess_alist, and then causes a GC, tail is an unprotected
6672 reference. */
6673 GCPRO2 (tail, msg);
6674
6675 /* Set this now, so that if new processes are created by sentinels
6676 that we run, we get called again to handle their status changes. */
6677 update_tick = process_tick;
6678
6679 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6680 {
6681 Lisp_Object symbol;
6682 register struct Lisp_Process *p;
6683
6684 proc = Fcdr (XCAR (tail));
6685 p = XPROCESS (proc);
6686
6687 if (p->tick != p->update_tick)
6688 {
6689 p->update_tick = p->tick;
6690
6691 /* If process is still active, read any output that remains. */
6692 while (! EQ (p->filter, Qt)
6693 && ! EQ (p->status, Qconnect)
6694 && ! EQ (p->status, Qlisten)
6695 && ! EQ (p->command, Qt) /* Network process not stopped. */
6696 && p->infd >= 0
6697 && p != deleting_process
6698 && read_process_output (proc, p->infd) > 0);
6699
6700 buffer = p->buffer;
6701
6702 /* Get the text to use for the message. */
6703 if (p->raw_status_new)
6704 update_status (p);
6705 msg = status_message (p);
6706
6707 /* If process is terminated, deactivate it or delete it. */
6708 symbol = p->status;
6709 if (CONSP (p->status))
6710 symbol = XCAR (p->status);
6711
6712 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6713 || EQ (symbol, Qclosed))
6714 {
6715 if (delete_exited_processes)
6716 remove_process (proc);
6717 else
6718 deactivate_process (proc);
6719 }
6720
6721 /* The actions above may have further incremented p->tick.
6722 So set p->update_tick again
6723 so that an error in the sentinel will not cause
6724 this code to be run again. */
6725 p->update_tick = p->tick;
6726 /* Now output the message suitably. */
6727 if (!NILP (p->sentinel))
6728 exec_sentinel (proc, msg);
6729 /* Don't bother with a message in the buffer
6730 when a process becomes runnable. */
6731 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6732 {
6733 Lisp_Object ro, tem;
6734 struct buffer *old = current_buffer;
6735 int opoint, opoint_byte;
6736 int before, before_byte;
6737
6738 ro = XBUFFER (buffer)->read_only;
6739
6740 /* Avoid error if buffer is deleted
6741 (probably that's why the process is dead, too) */
6742 if (NILP (XBUFFER (buffer)->name))
6743 continue;
6744 Fset_buffer (buffer);
6745
6746 opoint = PT;
6747 opoint_byte = PT_BYTE;
6748 /* Insert new output into buffer
6749 at the current end-of-output marker,
6750 thus preserving logical ordering of input and output. */
6751 if (XMARKER (p->mark)->buffer)
6752 Fgoto_char (p->mark);
6753 else
6754 SET_PT_BOTH (ZV, ZV_BYTE);
6755
6756 before = PT;
6757 before_byte = PT_BYTE;
6758
6759 tem = current_buffer->read_only;
6760 current_buffer->read_only = Qnil;
6761 insert_string ("\nProcess ");
6762 Finsert (1, &p->name);
6763 insert_string (" ");
6764 Finsert (1, &msg);
6765 current_buffer->read_only = tem;
6766 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6767
6768 if (opoint >= before)
6769 SET_PT_BOTH (opoint + (PT - before),
6770 opoint_byte + (PT_BYTE - before_byte));
6771 else
6772 SET_PT_BOTH (opoint, opoint_byte);
6773
6774 set_buffer_internal (old);
6775 }
6776 }
6777 } /* end for */
6778
6779 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6780 redisplay_preserve_echo_area (13);
6781
6782 UNGCPRO;
6783 }
6784
6785 \f
6786 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6787 Sset_process_coding_system, 1, 3, 0,
6788 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6789 DECODING will be used to decode subprocess output and ENCODING to
6790 encode subprocess input. */)
6791 (process, decoding, encoding)
6792 register Lisp_Object process, decoding, encoding;
6793 {
6794 register struct Lisp_Process *p;
6795
6796 CHECK_PROCESS (process);
6797 p = XPROCESS (process);
6798 if (p->infd < 0)
6799 error ("Input file descriptor of %s closed", SDATA (p->name));
6800 if (p->outfd < 0)
6801 error ("Output file descriptor of %s closed", SDATA (p->name));
6802 Fcheck_coding_system (decoding);
6803 Fcheck_coding_system (encoding);
6804 encoding = coding_inherit_eol_type (encoding, Qnil);
6805 p->decode_coding_system = decoding;
6806 p->encode_coding_system = encoding;
6807 setup_process_coding_systems (process);
6808
6809 return Qnil;
6810 }
6811
6812 DEFUN ("process-coding-system",
6813 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6814 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6815 (process)
6816 register Lisp_Object process;
6817 {
6818 CHECK_PROCESS (process);
6819 return Fcons (XPROCESS (process)->decode_coding_system,
6820 XPROCESS (process)->encode_coding_system);
6821 }
6822
6823 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6824 Sset_process_filter_multibyte, 2, 2, 0,
6825 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6826 If FLAG is non-nil, the filter is given multibyte strings.
6827 If FLAG is nil, the filter is given unibyte strings. In this case,
6828 all character code conversion except for end-of-line conversion is
6829 suppressed. */)
6830 (process, flag)
6831 Lisp_Object process, flag;
6832 {
6833 register struct Lisp_Process *p;
6834
6835 CHECK_PROCESS (process);
6836 p = XPROCESS (process);
6837 p->filter_multibyte = !NILP (flag);
6838 setup_process_coding_systems (process);
6839
6840 return Qnil;
6841 }
6842
6843 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6844 Sprocess_filter_multibyte_p, 1, 1, 0,
6845 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6846 (process)
6847 Lisp_Object process;
6848 {
6849 register struct Lisp_Process *p;
6850
6851 CHECK_PROCESS (process);
6852 p = XPROCESS (process);
6853
6854 return (p->filter_multibyte ? Qt : Qnil);
6855 }
6856
6857
6858 \f
6859 /* Add DESC to the set of keyboard input descriptors. */
6860
6861 void
6862 add_keyboard_wait_descriptor (desc)
6863 int desc;
6864 {
6865 FD_SET (desc, &input_wait_mask);
6866 FD_SET (desc, &non_process_wait_mask);
6867 if (desc > max_keyboard_desc)
6868 max_keyboard_desc = desc;
6869 }
6870
6871 static int add_gpm_wait_descriptor_called_flag;
6872
6873 void
6874 add_gpm_wait_descriptor (desc)
6875 int desc;
6876 {
6877 if (! add_gpm_wait_descriptor_called_flag)
6878 FD_CLR (0, &input_wait_mask);
6879 add_gpm_wait_descriptor_called_flag = 1;
6880 FD_SET (desc, &input_wait_mask);
6881 FD_SET (desc, &gpm_wait_mask);
6882 if (desc > max_gpm_desc)
6883 max_gpm_desc = desc;
6884 }
6885
6886 /* From now on, do not expect DESC to give keyboard input. */
6887
6888 void
6889 delete_keyboard_wait_descriptor (desc)
6890 int desc;
6891 {
6892 int fd;
6893 int lim = max_keyboard_desc;
6894
6895 FD_CLR (desc, &input_wait_mask);
6896 FD_CLR (desc, &non_process_wait_mask);
6897
6898 if (desc == max_keyboard_desc)
6899 for (fd = 0; fd < lim; fd++)
6900 if (FD_ISSET (fd, &input_wait_mask)
6901 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6902 && !FD_ISSET (fd, &gpm_wait_mask))
6903 max_keyboard_desc = fd;
6904 }
6905
6906 void
6907 delete_gpm_wait_descriptor (desc)
6908 int desc;
6909 {
6910 int fd;
6911 int lim = max_gpm_desc;
6912
6913 FD_CLR (desc, &input_wait_mask);
6914 FD_CLR (desc, &non_process_wait_mask);
6915
6916 if (desc == max_gpm_desc)
6917 for (fd = 0; fd < lim; fd++)
6918 if (FD_ISSET (fd, &input_wait_mask)
6919 && !FD_ISSET (fd, &non_keyboard_wait_mask)
6920 && !FD_ISSET (fd, &non_process_wait_mask))
6921 max_gpm_desc = fd;
6922 }
6923
6924 /* Return nonzero if *MASK has a bit set
6925 that corresponds to one of the keyboard input descriptors. */
6926
6927 static int
6928 keyboard_bit_set (mask)
6929 SELECT_TYPE *mask;
6930 {
6931 int fd;
6932
6933 for (fd = 0; fd <= max_keyboard_desc; fd++)
6934 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
6935 && !FD_ISSET (fd, &non_keyboard_wait_mask))
6936 return 1;
6937
6938 return 0;
6939 }
6940 \f
6941 void
6942 init_process ()
6943 {
6944 register int i;
6945
6946 inhibit_sentinels = 0;
6947
6948 #ifdef SIGCHLD
6949 #ifndef CANNOT_DUMP
6950 if (! noninteractive || initialized)
6951 #endif
6952 signal (SIGCHLD, sigchld_handler);
6953 #endif
6954
6955 FD_ZERO (&input_wait_mask);
6956 FD_ZERO (&non_keyboard_wait_mask);
6957 FD_ZERO (&non_process_wait_mask);
6958 max_process_desc = 0;
6959
6960 #ifdef NON_BLOCKING_CONNECT
6961 FD_ZERO (&connect_wait_mask);
6962 num_pending_connects = 0;
6963 #endif
6964
6965 #ifdef ADAPTIVE_READ_BUFFERING
6966 process_output_delay_count = 0;
6967 process_output_skip = 0;
6968 #endif
6969
6970 /* Don't do this, it caused infinite select loops. The display
6971 method should call add_keyboard_wait_descriptor on stdin if it
6972 needs that. */
6973 #if 0
6974 FD_SET (0, &input_wait_mask);
6975 #endif
6976
6977 Vprocess_alist = Qnil;
6978 #ifdef SIGCHLD
6979 deleted_pid_list = Qnil;
6980 #endif
6981 for (i = 0; i < MAXDESC; i++)
6982 {
6983 chan_process[i] = Qnil;
6984 proc_buffered_char[i] = -1;
6985 }
6986 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
6987 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
6988 #ifdef DATAGRAM_SOCKETS
6989 bzero (datagram_address, sizeof datagram_address);
6990 #endif
6991
6992 #ifdef HAVE_SOCKETS
6993 {
6994 Lisp_Object subfeatures = Qnil;
6995 struct socket_options *sopt;
6996
6997 #define ADD_SUBFEATURE(key, val) \
6998 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
6999
7000 #ifdef NON_BLOCKING_CONNECT
7001 ADD_SUBFEATURE (QCnowait, Qt);
7002 #endif
7003 #ifdef DATAGRAM_SOCKETS
7004 ADD_SUBFEATURE (QCtype, Qdatagram);
7005 #endif
7006 #ifdef HAVE_LOCAL_SOCKETS
7007 ADD_SUBFEATURE (QCfamily, Qlocal);
7008 #endif
7009 ADD_SUBFEATURE (QCfamily, Qipv4);
7010 #ifdef AF_INET6
7011 ADD_SUBFEATURE (QCfamily, Qipv6);
7012 #endif
7013 #ifdef HAVE_GETSOCKNAME
7014 ADD_SUBFEATURE (QCservice, Qt);
7015 #endif
7016 #if !defined(TERM) && (defined(O_NONBLOCK) || defined(O_NDELAY))
7017 ADD_SUBFEATURE (QCserver, Qt);
7018 #endif
7019
7020 for (sopt = socket_options; sopt->name; sopt++)
7021 subfeatures = Fcons (intern (sopt->name), subfeatures);
7022
7023 Fprovide (intern ("make-network-process"), subfeatures);
7024 }
7025 #endif /* HAVE_SOCKETS */
7026
7027 #if defined (DARWIN) || defined (MAC_OSX)
7028 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7029 processes. As such, we only change the default value. */
7030 if (initialized)
7031 {
7032 char *release = get_operating_system_release();
7033 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7034 && release[1] == '.')) {
7035 Vprocess_connection_type = Qnil;
7036 }
7037 }
7038 #endif
7039 }
7040
7041 void
7042 syms_of_process ()
7043 {
7044 Qprocessp = intern ("processp");
7045 staticpro (&Qprocessp);
7046 Qrun = intern ("run");
7047 staticpro (&Qrun);
7048 Qstop = intern ("stop");
7049 staticpro (&Qstop);
7050 Qsignal = intern ("signal");
7051 staticpro (&Qsignal);
7052
7053 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7054 here again.
7055
7056 Qexit = intern ("exit");
7057 staticpro (&Qexit); */
7058
7059 Qopen = intern ("open");
7060 staticpro (&Qopen);
7061 Qclosed = intern ("closed");
7062 staticpro (&Qclosed);
7063 Qconnect = intern ("connect");
7064 staticpro (&Qconnect);
7065 Qfailed = intern ("failed");
7066 staticpro (&Qfailed);
7067 Qlisten = intern ("listen");
7068 staticpro (&Qlisten);
7069 Qlocal = intern ("local");
7070 staticpro (&Qlocal);
7071 Qipv4 = intern ("ipv4");
7072 staticpro (&Qipv4);
7073 #ifdef AF_INET6
7074 Qipv6 = intern ("ipv6");
7075 staticpro (&Qipv6);
7076 #endif
7077 Qdatagram = intern ("datagram");
7078 staticpro (&Qdatagram);
7079
7080 QCname = intern (":name");
7081 staticpro (&QCname);
7082 QCbuffer = intern (":buffer");
7083 staticpro (&QCbuffer);
7084 QChost = intern (":host");
7085 staticpro (&QChost);
7086 QCservice = intern (":service");
7087 staticpro (&QCservice);
7088 QCtype = intern (":type");
7089 staticpro (&QCtype);
7090 QClocal = intern (":local");
7091 staticpro (&QClocal);
7092 QCremote = intern (":remote");
7093 staticpro (&QCremote);
7094 QCcoding = intern (":coding");
7095 staticpro (&QCcoding);
7096 QCserver = intern (":server");
7097 staticpro (&QCserver);
7098 QCnowait = intern (":nowait");
7099 staticpro (&QCnowait);
7100 QCsentinel = intern (":sentinel");
7101 staticpro (&QCsentinel);
7102 QClog = intern (":log");
7103 staticpro (&QClog);
7104 QCnoquery = intern (":noquery");
7105 staticpro (&QCnoquery);
7106 QCstop = intern (":stop");
7107 staticpro (&QCstop);
7108 QCoptions = intern (":options");
7109 staticpro (&QCoptions);
7110 QCplist = intern (":plist");
7111 staticpro (&QCplist);
7112 QCfilter_multibyte = intern (":filter-multibyte");
7113 staticpro (&QCfilter_multibyte);
7114
7115 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7116 staticpro (&Qlast_nonmenu_event);
7117
7118 staticpro (&Vprocess_alist);
7119 #ifdef SIGCHLD
7120 staticpro (&deleted_pid_list);
7121 #endif
7122
7123 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7124 doc: /* *Non-nil means delete processes immediately when they exit.
7125 A value of nil means don't delete them until `list-processes' is run. */);
7126
7127 delete_exited_processes = 1;
7128
7129 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7130 doc: /* Control type of device used to communicate with subprocesses.
7131 Values are nil to use a pipe, or t or `pty' to use a pty.
7132 The value has no effect if the system has no ptys or if all ptys are busy:
7133 then a pipe is used in any case.
7134 The value takes effect when `start-process' is called. */);
7135 Vprocess_connection_type = Qt;
7136
7137 #ifdef ADAPTIVE_READ_BUFFERING
7138 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7139 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7140 On some systems, when Emacs reads the output from a subprocess, the output data
7141 is read in very small blocks, potentially resulting in very poor performance.
7142 This behavior can be remedied to some extent by setting this variable to a
7143 non-nil value, as it will automatically delay reading from such processes, to
7144 allow them to produce more output before Emacs tries to read it.
7145 If the value is t, the delay is reset after each write to the process; any other
7146 non-nil value means that the delay is not reset on write.
7147 The variable takes effect when `start-process' is called. */);
7148 Vprocess_adaptive_read_buffering = Qt;
7149 #endif
7150
7151 defsubr (&Sprocessp);
7152 defsubr (&Sget_process);
7153 defsubr (&Sget_buffer_process);
7154 defsubr (&Sdelete_process);
7155 defsubr (&Sprocess_status);
7156 defsubr (&Sprocess_exit_status);
7157 defsubr (&Sprocess_id);
7158 defsubr (&Sprocess_name);
7159 defsubr (&Sprocess_tty_name);
7160 defsubr (&Sprocess_command);
7161 defsubr (&Sset_process_buffer);
7162 defsubr (&Sprocess_buffer);
7163 defsubr (&Sprocess_mark);
7164 defsubr (&Sset_process_filter);
7165 defsubr (&Sprocess_filter);
7166 defsubr (&Sset_process_sentinel);
7167 defsubr (&Sprocess_sentinel);
7168 defsubr (&Sset_process_window_size);
7169 defsubr (&Sset_process_inherit_coding_system_flag);
7170 defsubr (&Sprocess_inherit_coding_system_flag);
7171 defsubr (&Sset_process_query_on_exit_flag);
7172 defsubr (&Sprocess_query_on_exit_flag);
7173 defsubr (&Sprocess_contact);
7174 defsubr (&Sprocess_plist);
7175 defsubr (&Sset_process_plist);
7176 defsubr (&Slist_processes);
7177 defsubr (&Sprocess_list);
7178 defsubr (&Sstart_process);
7179 #ifdef HAVE_SOCKETS
7180 defsubr (&Sset_network_process_option);
7181 defsubr (&Smake_network_process);
7182 defsubr (&Sformat_network_address);
7183 #endif /* HAVE_SOCKETS */
7184 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7185 #ifdef SIOCGIFCONF
7186 defsubr (&Snetwork_interface_list);
7187 #endif
7188 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7189 defsubr (&Snetwork_interface_info);
7190 #endif
7191 #endif /* HAVE_SOCKETS ... */
7192 #ifdef DATAGRAM_SOCKETS
7193 defsubr (&Sprocess_datagram_address);
7194 defsubr (&Sset_process_datagram_address);
7195 #endif
7196 defsubr (&Saccept_process_output);
7197 defsubr (&Sprocess_send_region);
7198 defsubr (&Sprocess_send_string);
7199 defsubr (&Sinterrupt_process);
7200 defsubr (&Skill_process);
7201 defsubr (&Squit_process);
7202 defsubr (&Sstop_process);
7203 defsubr (&Scontinue_process);
7204 defsubr (&Sprocess_running_child_p);
7205 defsubr (&Sprocess_send_eof);
7206 defsubr (&Ssignal_process);
7207 defsubr (&Swaiting_for_user_input_p);
7208 /* defsubr (&Sprocess_connection); */
7209 defsubr (&Sset_process_coding_system);
7210 defsubr (&Sprocess_coding_system);
7211 defsubr (&Sset_process_filter_multibyte);
7212 defsubr (&Sprocess_filter_multibyte_p);
7213 }
7214
7215 \f
7216 #else /* not subprocesses */
7217
7218 #include <sys/types.h>
7219 #include <errno.h>
7220
7221 #include "lisp.h"
7222 #include "systime.h"
7223 #include "character.h"
7224 #include "coding.h"
7225 #include "termopts.h"
7226 #include "sysselect.h"
7227
7228 extern int frame_garbaged;
7229
7230 extern EMACS_TIME timer_check ();
7231 extern int timers_run;
7232
7233 Lisp_Object QCtype;
7234
7235 /* As described above, except assuming that there are no subprocesses:
7236
7237 Wait for timeout to elapse and/or keyboard input to be available.
7238
7239 time_limit is:
7240 timeout in seconds, or
7241 zero for no limit, or
7242 -1 means gobble data immediately available but don't wait for any.
7243
7244 read_kbd is a Lisp_Object:
7245 0 to ignore keyboard input, or
7246 1 to return when input is available, or
7247 -1 means caller will actually read the input, so don't throw to
7248 the quit handler.
7249
7250 see full version for other parameters. We know that wait_proc will
7251 always be NULL, since `subprocesses' isn't defined.
7252
7253 do_display != 0 means redisplay should be done to show subprocess
7254 output that arrives.
7255
7256 Return true if we received input from any process. */
7257
7258 int
7259 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7260 wait_for_cell, wait_proc, just_wait_proc)
7261 int time_limit, microsecs, read_kbd, do_display;
7262 Lisp_Object wait_for_cell;
7263 struct Lisp_Process *wait_proc;
7264 int just_wait_proc;
7265 {
7266 register int nfds;
7267 EMACS_TIME end_time, timeout;
7268 SELECT_TYPE waitchannels;
7269 int xerrno;
7270
7271 /* What does time_limit really mean? */
7272 if (time_limit || microsecs)
7273 {
7274 EMACS_GET_TIME (end_time);
7275 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7276 EMACS_ADD_TIME (end_time, end_time, timeout);
7277 }
7278
7279 /* Turn off periodic alarms (in case they are in use)
7280 and then turn off any other atimers,
7281 because the select emulator uses alarms. */
7282 stop_polling ();
7283 turn_on_atimers (0);
7284
7285 while (1)
7286 {
7287 int timeout_reduced_for_timers = 0;
7288
7289 /* If calling from keyboard input, do not quit
7290 since we want to return C-g as an input character.
7291 Otherwise, do pending quit if requested. */
7292 if (read_kbd >= 0)
7293 QUIT;
7294
7295 /* Exit now if the cell we're waiting for became non-nil. */
7296 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7297 break;
7298
7299 /* Compute time from now till when time limit is up */
7300 /* Exit if already run out */
7301 if (time_limit == -1)
7302 {
7303 /* -1 specified for timeout means
7304 gobble output available now
7305 but don't wait at all. */
7306
7307 EMACS_SET_SECS_USECS (timeout, 0, 0);
7308 }
7309 else if (time_limit || microsecs)
7310 {
7311 EMACS_GET_TIME (timeout);
7312 EMACS_SUB_TIME (timeout, end_time, timeout);
7313 if (EMACS_TIME_NEG_P (timeout))
7314 break;
7315 }
7316 else
7317 {
7318 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7319 }
7320
7321 /* If our caller will not immediately handle keyboard events,
7322 run timer events directly.
7323 (Callers that will immediately read keyboard events
7324 call timer_delay on their own.) */
7325 if (NILP (wait_for_cell))
7326 {
7327 EMACS_TIME timer_delay;
7328
7329 do
7330 {
7331 int old_timers_run = timers_run;
7332 timer_delay = timer_check (1);
7333 if (timers_run != old_timers_run && do_display)
7334 /* We must retry, since a timer may have requeued itself
7335 and that could alter the time delay. */
7336 redisplay_preserve_echo_area (14);
7337 else
7338 break;
7339 }
7340 while (!detect_input_pending ());
7341
7342 /* If there is unread keyboard input, also return. */
7343 if (read_kbd != 0
7344 && requeued_events_pending_p ())
7345 break;
7346
7347 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7348 {
7349 EMACS_TIME difference;
7350 EMACS_SUB_TIME (difference, timer_delay, timeout);
7351 if (EMACS_TIME_NEG_P (difference))
7352 {
7353 timeout = timer_delay;
7354 timeout_reduced_for_timers = 1;
7355 }
7356 }
7357 }
7358
7359 /* Cause C-g and alarm signals to take immediate action,
7360 and cause input available signals to zero out timeout. */
7361 if (read_kbd < 0)
7362 set_waiting_for_input (&timeout);
7363
7364 /* Wait till there is something to do. */
7365
7366 if (! read_kbd && NILP (wait_for_cell))
7367 FD_ZERO (&waitchannels);
7368 else
7369 FD_SET (0, &waitchannels);
7370
7371 /* If a frame has been newly mapped and needs updating,
7372 reprocess its display stuff. */
7373 if (frame_garbaged && do_display)
7374 {
7375 clear_waiting_for_input ();
7376 redisplay_preserve_echo_area (15);
7377 if (read_kbd < 0)
7378 set_waiting_for_input (&timeout);
7379 }
7380
7381 if (read_kbd && detect_input_pending ())
7382 {
7383 nfds = 0;
7384 FD_ZERO (&waitchannels);
7385 }
7386 else
7387 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7388 &timeout);
7389
7390 xerrno = errno;
7391
7392 /* Make C-g and alarm signals set flags again */
7393 clear_waiting_for_input ();
7394
7395 /* If we woke up due to SIGWINCH, actually change size now. */
7396 do_pending_window_change (0);
7397
7398 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7399 /* We waited the full specified time, so return now. */
7400 break;
7401
7402 if (nfds == -1)
7403 {
7404 /* If the system call was interrupted, then go around the
7405 loop again. */
7406 if (xerrno == EINTR)
7407 FD_ZERO (&waitchannels);
7408 else
7409 error ("select error: %s", emacs_strerror (xerrno));
7410 }
7411 #ifdef sun
7412 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7413 /* System sometimes fails to deliver SIGIO. */
7414 kill (getpid (), SIGIO);
7415 #endif
7416 #ifdef SIGIO
7417 if (read_kbd && interrupt_input && (waitchannels & 1))
7418 kill (getpid (), SIGIO);
7419 #endif
7420
7421 /* Check for keyboard input */
7422
7423 if (read_kbd
7424 && detect_input_pending_run_timers (do_display))
7425 {
7426 swallow_events (do_display);
7427 if (detect_input_pending_run_timers (do_display))
7428 break;
7429 }
7430
7431 /* If there is unread keyboard input, also return. */
7432 if (read_kbd
7433 && requeued_events_pending_p ())
7434 break;
7435
7436 /* If wait_for_cell. check for keyboard input
7437 but don't run any timers.
7438 ??? (It seems wrong to me to check for keyboard
7439 input at all when wait_for_cell, but the code
7440 has been this way since July 1994.
7441 Try changing this after version 19.31.) */
7442 if (! NILP (wait_for_cell)
7443 && detect_input_pending ())
7444 {
7445 swallow_events (do_display);
7446 if (detect_input_pending ())
7447 break;
7448 }
7449
7450 /* Exit now if the cell we're waiting for became non-nil. */
7451 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7452 break;
7453 }
7454
7455 start_polling ();
7456
7457 return 0;
7458 }
7459
7460
7461 /* Don't confuse make-docfile by having two doc strings for this function.
7462 make-docfile does not pay attention to #if, for good reason! */
7463 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7464 0)
7465 (name)
7466 register Lisp_Object name;
7467 {
7468 return Qnil;
7469 }
7470
7471 /* Don't confuse make-docfile by having two doc strings for this function.
7472 make-docfile does not pay attention to #if, for good reason! */
7473 DEFUN ("process-inherit-coding-system-flag",
7474 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7475 1, 1, 0,
7476 0)
7477 (process)
7478 register Lisp_Object process;
7479 {
7480 /* Ignore the argument and return the value of
7481 inherit-process-coding-system. */
7482 return inherit_process_coding_system ? Qt : Qnil;
7483 }
7484
7485 /* Kill all processes associated with `buffer'.
7486 If `buffer' is nil, kill all processes.
7487 Since we have no subprocesses, this does nothing. */
7488
7489 void
7490 kill_buffer_processes (buffer)
7491 Lisp_Object buffer;
7492 {
7493 }
7494
7495 void
7496 init_process ()
7497 {
7498 }
7499
7500 void
7501 syms_of_process ()
7502 {
7503 QCtype = intern (":type");
7504 staticpro (&QCtype);
7505
7506 defsubr (&Sget_buffer_process);
7507 defsubr (&Sprocess_inherit_coding_system_flag);
7508 }
7509
7510 \f
7511 #endif /* not subprocesses */
7512
7513 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7514 (do not change this comment) */