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