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