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