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